Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 541
Rahul Gupta Avatar asked Dec 09 '22 11:12

Rahul Gupta


1 Answers

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();
   }
}
like image 55
Dharmendra Avatar answered Dec 26 '22 02:12

Dharmendra