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?
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() ."
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.
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.
it means your calling a fragment method
((YourFragmentClass) fragment).Yourmethod();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With