How to call a fragment method from the main action

I have a method in a fragment class. I want to call this method from the main action, but I do not want to use FragmentById (or) FragmentByTag.

My fragment method:

public void setItemFromDrawer(String sourceTag, String destTag) { //dosomething } 

How to call the method above from the main action without using FragmentById (or) FragmentByTag?

+7
java android android-activity android-fragments android-fragmentmanager
source share
4 answers

First create an interface

 public interface MyInterface { void myAction() ; } 

Your snippet should 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 a fragment and adding it:

 setListener(myFragment); 

Finally, when the condition arises that you want to call the Fragment method, simply call:

 listener.myAction() ; // this will call the implementation in your MyFragment class. 
+19
source share

that means you call the fragment method

 ((YourFragmentClass) fragment).Yourmethod(); 
+4
source share

In action, use something like this when you load a snippet:

 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 the following line where you want to call the fragment method

 currentFragment.setItemFromDrawer("sourceTag","destTag"); 
+1
source share

((a fragment of your Fragment class)). Your method ();

it worked form me

-3
source share

All Articles