android implement listener in fragment - android

I am new in Android development. I want to add a listener in my fragment which upon button click will send a message. I need to listen to this in my main fragment class so that my activity can access this main fragment and process the message. I also need to remove the listener in my main fragment. So how do I implement this?
EDIT
I have MyFragment
sendMessage(message) is a method in MyFragment which has a button click. Need to implement listener here?
In MainFragment
How to handle this sendMessage event here and send to MAinActivity
The flow is like MyFragment(childfragment) -> MAinFragment -> MainActivity

In your fragment class, say MyFragment.java create an interface
public interface MyFragmentInterfacer{
void onButtonClick(String msg);
}
MyFragmentInterfacer fragmentInterfacer;
//Override this function as below to set fragmentInterfacer
#Override
public void onAttach(Context context){
fragmentInterfacer = (MyFragmentInterfacer)context;
}
and where you want to invoke this function
myButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
if(fragmentInterfacer != null){
fragmentInterfacer.onButtonClick("This is my Message");
}
}
});
Then in your main activity where you want to get this message, implement this interface
public class MainActivity implements MyFragment.MyFragmentInterfacer{
.
.
}
and then implement the interface function in MainActivity
#Override
public void onButtonClick(String msg){
//Do something with this message
}
To remove this listener, use
fragmentInterfacer = null;
in your fragment class when you want to disable this listener.
Or you can remove the onClickListener from button
myButton.setOnClickListener(null);
or disable clicking on button
myButton.setClickable(false);

Related

What is the correct way to set a listener to a fragment from an "independent" manager class?

Suppose I have an Activity or a Fragment that uses a manager class which dislpays a DialogFragment, and that manager class needs to listen to some of the DialogFragment events.
What is the correct way to set a listener to the DialogFragment from the manager class, without depending on the Activity or Fragment that is using it?
Activity ---uses---> Manager ---displays---> DialogFragment
Yes, you can create an Interface listener implement that listener on your manager class and pass the reference of that Listener interface to your dialog class whenever you click it will call the manager class method. Example -
public interface ICallbackListener {
void onCallbackListener();
}
public class ManagerClass implement ICallbackListener{
#Override
public void onCallbackListener(){
// do whatever you want to do.....
}
// pass this method to your dialog....
public void getListner(){
return this;
}
}
// just a demo
public class CustomDialog extent Dialog{
ICallbackListener listener;
public CustomDialog(ICallbackListener listener){
this.listener = listener;}
// so from where you want to send data just call this
// listener.onCallbackListener();
}

How can I Perform networking(save results in the database using volley) based on the result I got from a fragment?

I have an activity and a fragment. If I click a button then a fragment is called. Upon the result I got from the fragment I need some networking call to perform using volley. But I can't do any networking call from activity unless I call this within onClick() method.
I tried to perform networking from within onClick() of the fragment but that did not worked too.
How can i perform networking from the activity upon the result I got from the fragment? Do I must call from within onClick()?
This is the fragment
This is the Activity
I think that you can use callback.
Create intefrace and declare method saveResult() in it.
public interface YourInterface{
void saveResult();
}
After that your Activity must implement this interface and add your code for save result in database in saveResult method body
public class YourActivity implements YourInterface{
#override
void saveResult(){
//your code here
}
}
And finnaly in your fragment call method when you whant or when your fragment is ready.You can call method with help of
callBack.saveResult();
You must override onAttach in your fragment and there must initialize your callback
YourInterface callback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if(activity instanceof YourInterface ) {
callback = (YourInterface ) activity;
}
}
Try with other on click method in at your onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mark_distribution);
assign_buttton=(Button)findViewById(R.id.assign_marks);
view_buttton=(Button)findViewById(R.id.view_marks);
update_buttton=(Button)findViewById(R.id.update_marks);
//Like this-->>>
update_buttton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
marks_type=(String)assigned_marks_type.getText().toString();
marks=Integer.parseInt(assigned_marks.getText().toString().trim());
callback.saveResult(marks_type,marks);
}
});
//********************/
Intent i=getIntent();
course_title= i.getExtras().getString("COURSE_TITLE");
}
Hope to help you!

Android setOnClickListener method - How does it work?

I have trouble understanding this code. I get that findViewById will get the button widget and then it'll cast it. Then, it's going to use the button to call the setOnClickListener method. However, I don't know what is that argument being passed into the setOnClickListener and I have never seen code like that before. How is it that it creates a new object but is able to create a method of its own within another method's argument? Would be great if someone could explain that. Also, what type of object is the setOnClickListener method taking in?
btn = (Button)findViewById(R.id.firstButton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
tv.setText(months[rand.nextInt(12)]);
tv.setTextColor(Color.rgb(rand.nextInt(255)+1, rand.nextInt(255)+1, rand.nextInt(255)+1));
}
});
It works like this. View.OnClickListenere is defined -
public interface OnClickListener {
void onClick(View v);
}
As far as we know you cannot instantiate an object OnClickListener, as it doesn't have a method implemented. So there are two ways you can go by - you can implement this interface which will override onClick method like this:
public class MyListener implements View.OnClickListener {
#Override
public void onClick (View v) {
// your code here;
}
}
But it's tedious to do it each time as you want to set a click listener. So in order to avoid this you can provide the implementation for the method on spot, just like in an example you gave.
setOnClickListener takes View.OnClickListener as its parameter.
This is the best way to implement Onclicklistener for many buttons in a row
implement View.onclicklistener.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
This is a button in the MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_submit = (Button) findViewById(R.id.submit);
bt_submit.setOnClickListener(this);
}
This is an override method
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.submit:
//action
break;
case R.id.secondbutton:
//action
break;
}
}
That what manual says about setOnClickListener method is:
public void setOnClickListener (View.OnClickListener l)
Added in API level 1 Register a callback to be invoked when this view
is clicked. If this view is not clickable, it becomes clickable.
Parameters
l View.OnClickListener: The callback that will run
And normally you have to use it like this
public class ExampleActivity extends Activity implements OnClickListener {
protected void onCreate(Bundle savedValues) {
...
Button button = (Button)findViewById(R.id.corky);
button.setOnClickListener(this);
}
// Implement the OnClickListener callback
public void onClick(View v) {
// do something when the button is clicked
}
...
}
Take a look at this lesson as well Building a Simple Calculator using Android Studio.
its an implementation of anonymouse class object creation to give ease of writing less code and to save time
It works by same principle of anonymous inner class where we can instantiate an interface without actually defining a class :
Ref: https://www.geeksforgeeks.org/anonymous-inner-class-java/

How Send message from fragment to activity and received and use in activity?

Please please don't minus my question i confused when googling.
I used Android Tab Layout with Swipeable Views in my code for when user pressed setting button on an activity.
now I need send message from TopRatedFragment.java that extends from fragment to the activity that call the mainActivity of "Android Tab Layout with Swipeable Views".
You can do this by implementing a call back
create an interface first
public interface CommunicationInterface {
public void onSuccess();
public void onFailed();
}
then in your activity implement the interface
public class YourActivity extends ActionBarActivity implements CommunicationInterface {
//default functions
#Override
public void onSuccess() {
//stuff you want to do in the acivity
}
#Override
public void onFailed() {
//stuff you want to do in the acivity
}
}
Now in the fragment
public class yourfragment extends Fragment {
CommunicationInterface callback;
//stuffs that usually come in yor fragment and like OncreateView etc
#Override
public void onActivityCreated(#Nullable Bundle outState) {
super.onActivityCreated(outState);
//after all the stuff you want to do in your fragment then implement //call back function to communicate with the activity
callback= (CommunicationInterface) getActivity();
callback.onSuccess();//according to your purpose use where ever you like
callback.onFailed();//according to your purpose use where ever you like
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
callback= (CommunicationInterface) activity;
}
}
Take a close look on this reference:
Creating event callbacks to the activity
The android docs recommend using this pattern of having the parent activity implement an interface of the fragment (Basically calling methods on it)
class MyFragment extends Fragment {
interface Listener {
public void onSomeEvent();
}
private void somethingHappeninInTheFragment() {
// let the activity know
((Listener) getActivity()).onSomeEVent();
}
}
class MyActivity extends Activity implements MyFragment.Listener {
// etc
#Override
public void onSomeEvent() {
// handle the message from the fragment
}
}
Explained with a more concrete example here: http://developer.android.com/guide/components/fragments.html#EventCallbacks
Here's the solution:
Step 1 : From your fragment.
Intent i = new Intent(getActivity(), YourActivity.class);
i.putExtra("key", "Your value1");
i.putExtra("key2", "Your value2");
i.putExtra("key3", "Your value3");
getActivity().startActivity(i);
Step 2 : In your Activity where you want the result
Intent getResults = getIntent();
String firstValue = getResults.getStringExtra("key1");
String secondValue = getResults.getStringExtra("key2");
String thirdValue = getResults.getStringExtra("key3");
Use those values your needs are.
Hope this helps.. :)

How to fire event from fragment in main activity?

I have a Main Activity having one edittext and a viewpager which is getting inflated via two fragments. Both fragment layout contain buttons. My question is how to fire their on click listener in main activity.
Like i have a button in one fragment which should change the text in my edittext bold using spannable string. I can achieve it if all of this is in my main activity. My question is how to capture the listener of this button in main activity ?
Create one interface and pass the instance to fragment and when button clicked from fragment call the method of interface so you will get callback to activity and from there you can update your UI.
for example:
public interface MyInterface {
public void buttonClicked();
}
public class Activity implements MyInterface {
#override
public void buttonClicked() {
//Change the UI
}
}
public class MyFragment extends Fragment {
MyInterface interface;
public void setInterface(MyInterface interface) {
this.interface = interface;
}
public void onClick(View v) {
interface.buttonClicked();
}
}
In your fragment, you can use
((MainActivity)getActivity()).myMethod()
to call myMethod of MainActivity. This solution assumes, that your fragment is located in MainActivity (getActivity must return MainActivity instance) :-)

Categories

Resources