How to call fragment method from main activity

后端 未结 5 855
遇见更好的自我
遇见更好的自我 2020-12-23 12:49

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:

5条回答
  •  再見小時候
    2020-12-23 13:15

    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.
    

提交回复
热议问题