Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...