How to call fragment method from main activity How to call fragment method from main activity android android

How to call fragment method from main activity


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.


it means your calling a fragment method

((YourFragmentClass) fragment).Yourmethod();


To better explain the answer by user5466222 :

YourFragmentClass fragment = new YourFragmentClass();((YourFragmentClass) fragment).yourmethod();