androidandroid-fragmentschild-fragment

Android child fragment not null after removing


I'm trying to run some operations based on whether a child fragment exists. Here is my code:

private void addChatFragment() {
    getChildFragmentManager()
            .beginTransaction()
            .add(R.id.chat_container, ChatFragment.newInstance(),
                    ChatFragment.FRAGMENT_TAG).commitAllowingStateLoss();
}

private void removeChatFragment() {
    ChatFragment f = (ChatFragment)getChildFragmentManager()
            .findFragmentByTag(ChatFragment.FRAGMENT_TAG);
    if(f != null) {
        getChildFragmentManager().beginTransaction().remove(f).commit();
    }

    Log.v("qwer", "is chat fragment null: " + getChildFragmentManager()
            .findFragmentByTag(ChatFragment.FRAGMENT_TAG));

}

The problem is my chat fragment is not null after I remove it. Is this expected behavior? And is there a way to completely "remove" to where the fragment is null?


Solution

  • FragmentTransaction#commit schedules a removal of the fragment, so it is done asynchronously. FragmentTransaction#commitNow does the removal synchronously.