How to call fragment method from main activity

后端 未结 5 850
遇见更好的自我
遇见更好的自我 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:06

    it means your calling a fragment method

    ((YourFragmentClass) fragment).Yourmethod();
    
    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2020-12-23 13:19

    In Activity use something like this where you load your fragment:

    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.replace(container, fragment);
    
    transaction.addToBackStack(null); // if you want to store transaction        
    transaction.commit();
    currentFragment = fragment; // currentFragment is global Fragment variable
    

    Use following line where you want to call fragment's method

    currentFragment.setItemFromDrawer("sourceTag","destTag");
    
    0 讨论(0)
  • 2020-12-23 13:21

    ((YourFragment Class) fragment).Your method();

    its worked form me

    0 讨论(0)
  • 2020-12-23 13:24

    To better explain the answer by user5466222 :

    YourFragmentClass fragment = new YourFragmentClass();
    ((YourFragmentClass) fragment).yourmethod();
    
    0 讨论(0)
提交回复
热议问题