0

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?

jwBurnside
  • 849
  • 4
  • 31
  • 66

2 Answers2

1

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

Brianvdb
  • 666
  • 1
  • 6
  • 16
0
FragmentTransaction.commitNow 

is for api 24 and more if your min api is lower than that you can use popBackStack() after commit().

 fragmentTransaction.remove(fragmentA);
 fragmentTransaction.commit();
 fragmentManager.popBackStack();
khoshrang
  • 146
  • 11
  • If you're using the support library versions, this is only half true. As long as you're using version 24.0.1 or later, it will work on any API level. – Ben P. Nov 17 '18 at 01:40