如何从主活动中调用片段方法 [英] How to call fragment method from main activity
问题描述
我在片段类中有方法。我想从主要活动中调用该方法,但我不想使用FragmentById(或)FragmentByTag。
我的片段方法:
public void setItemFromDrawer(String sourceTag,String destTag){
// dosomething
}
如何上述从主活性的方法调用,而无需使用FragmentById(或)FragmentByTag?
public interface MyInterface
{
void myAction();
}
您的片段必须实现此接口。
public MyFragment extends Fragment实现MyInterface
在您的活动中,定义MyInterface类型的字段:
私有MyInterface监听器;
public void setListener(MyInterface listener)
{
this.listener = listener;
}
创建片段并添加片段时:
setListener(myFragment);
最后,当你想要调用Fragment方法的condtion时,只需调用:
listener.myAction(); //这将调用MyFragment类中的实现。
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?
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屋!