How to call fragment method from main activity

hikoo picture hikoo · Mar 2, 2016 · Viewed 35.5k times · Source

I have method in fragment class. I want to call that method from main activity but I don't want to use FragmentById (or) FragmentByTag.

My fragment method:

public void setItemFromDrawer(String sourceTag, String destTag) {
    //dosomething
}

How to call above method from main activity without using FragmentById (or) FragmentByTag?

Answer

Farhad Faghihi picture Farhad Faghihi · Mar 2, 2016

First create an interface

public interface MyInterface
{
    void myAction() ;
}

Your fragment must implement this interface.

public MyFragment extends Fragment implements MyInterface

In your activity, define a field of type MyInterface :

  private MyInterface listener ;

  public void setListener(MyInterface listener)
  {
     this.listener = listener ;
  }

When creating your fragment and adding it :

setListener(myFragment);

Finally, when the condtion happens that you want to call the Fragment method, just call :

listener.myAction() ; // this will call the implementation in your MyFragment class.