findFragmentByTag() returns null after perform a FragmentTransaction using replace() method

前端 未结 8 1716
广开言路
广开言路 2020-11-30 04:44

My Android app consists three fragments: A, B and C. They\'re loaded in the two containers defined in the MainActivity layout.

When th

8条回答
  •  盖世英雄少女心
    2020-11-30 05:08

    I had the same problem and realized that there is a really simple way to fix this. When using a tag please do make sure to add the

    fragmentTransaction.addToBackStack(null); 
    

    method so that your Fragment is resumed instead of destroyed as mentioned in the developer guides.

    If you don't call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it. Whereas, if you do call addToBackStack() when removing a fragment, then the fragment is stopped and is later resumed if the user navigates back.

    You can find this at the end of this section.

    Every time I tried to reference back to my created Fragment, it turns out it had already been destroyed so I lost about 30 minutes trying to figure out why my Fragment was not being found through a simple findFragmentByTag(); call.

    Hope this helps!

提交回复
热议问题