简体   繁体   English

从另一个片段调用一个片段的方法

[英]Call method on a fragment from another fragment

How can i call a method on a fragment from another fragment? 如何从另一个片段调用一个片段的方法?

I tried: 我试过了:

Fragment fragmentName = (fragmentName) getFragmentManager().findFragmentByTag("fragmentTag");
fragmentName.method();

but it's a null pointer. 但这是一个空指针。

Thank you so much. 非常感谢。

You should not communicate directly between fragments (with exception of childfragments maybe). 您不应该在片段之间直接进行通信(可能会出现子片段)。 Instead, use your activity as mediator. 而是将您的活动用作调解人。

FragmentA {
    public void sendMessageToB(String message) {
        ((MainActivity)getActivity()).sendMessageToB(message);
    }
}

FragmentB {
    public void receiveMessage(String message) {

    }
}

MainActivity {
    public void sendMessageToB(String message) {
        // or findById if defined in XML (same as with Views)
        FragmentB fragment = (FragmentB) getFragmentManager().findFragmentByTag("FragmentB");
        if (fragment != null && fragment.isAdded()) {
            fragment.receiveMessage(message);
        }
    }
}

While you can actually use a code like that, it might not be a good practice since you are creating a dependency between the two fragments. 尽管实际上可以使用这样的代码,但这可能不是一个好习惯,因为您正在两个片段之间创建依赖关系。

The null pointer happens probably because when the code runs the other fragment is still not initialized. 空指针的出现可能是因为在代码运行时,另一个片段仍未初始化。 You might use some of the activity or fragment lifecycle methods (like onAttach) to run the code only after the target has been initialized. 您可能仅在初始化目标之后才使用某些活动或片段生命周期方法(如onAttach)来运行代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM