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

Categories

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

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

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...