4

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 ?

Rahul Gupta
  • 5,275
  • 8
  • 35
  • 66

2 Answers2

10

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();
   }
}
Dharmendra
  • 33,296
  • 22
  • 86
  • 129
5

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) :-)

Berťák
  • 7,143
  • 2
  • 29
  • 38