Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 480
hikoo Avatar asked Mar 02 '16 12:03

hikoo


People also ask

How can I call a fragment method from another activity?

Bookmark this question. Show activity on this post. I see in the Android Fragments Dev Guide that an "activity can call methods in a fragment by acquiring a reference to the Fragment from FragmentManager, using findFragmentById() or findFragmentByTag() ."

Can we navigate from activity to fragment?

If you want to go back from Activity to Fragment. This is very simple just override onBackPressed() in your activity and call onBackPressed where you want.


2 Answers

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.
like image 121
Farhad Faghihi Avatar answered Sep 20 '22 13:09

Farhad Faghihi


it means your calling a fragment method

((YourFragmentClass) fragment).Yourmethod();
like image 43
user5466222 Avatar answered Sep 18 '22 13:09

user5466222