我在 fragment 类中有方法。我想从主要 Activity 中调用该方法,但我不想使用 FragmentById(或)FragmentByTag。
我的 fragment 方法:
public void setItemFromDrawer(String sourceTag, String destTag) {
//dosomething
}
如何在不使用 FragmentById(或)FragmentByTag 的情况下从主 Activity 调用上述方法?
最佳答案
首先创建一个接口(interface)
public interface MyInterface
{
void myAction() ;
}
您的 fragment 必须实现此接口(interface)。
public MyFragment extends Fragment implements MyInterface
在您的 Activity 中,定义一个类型为 MyInterface 的字段:
private MyInterface listener ;
public void setListener(MyInterface listener)
{
this.listener = listener ;
}
创建 fragment 并添加它时:
setListener(myFragment);
最后,当你想调用 Fragment 方法的情况发生时,只需调用:
listener.myAction() ; // this will call the implementation in your MyFragment class.
关于java - 如何从主 Activity 调用 fragment 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35747346/