简体   繁体   中英

How to call fragment method from main activity

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?

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.

这意味着您调用片段方法

((YourFragmentClass) fragment).Yourmethod();

To better explain the answer by user5466222 :

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

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

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

its worked form me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM