简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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