How to call fragment method from main activity

[亡魂溺海] 提交于 2019-11-30 11:38:51

问题


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?


回答1:


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.



回答2:


it means your calling a fragment method

((YourFragmentClass) fragment).Yourmethod();



回答3:


To better explain the answer by user5466222 :

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



回答4:


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");



回答5:


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

its worked form me



来源:https://stackoverflow.com/questions/35747346/how-to-call-fragment-method-from-main-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!