android-calling findFragmentByTag immediately after committing transaction

Viewed 135

the common practice to replace a fragment by another fragment is:

getActivity().getSupportFragmentManager()
.beginTransaction()
.setReorderingAllowed(true)
.replace(R.id.fragment_holder, ItemFragment.newInstance(bundle),"tag")
.addToBackStack(null)
.commit();

the documentation for commit() method says:

Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.

now imagine I call getActivity.getSupportFragmentManager.findFragmentByTag("tag"); right after the commit method mentioned above. since the commit does not happen immediately, is it possible that it returns null?

2 Answers

I don't think it can return null if that was the case the documentation for findFragmentByTag("tag") would have stated that.

Also the method is from FragmentManager class so all it cares about whether or not is contained in the fragment manager the commit() function is from FragmentTransaction class a fragment can be in the back stack of fragment manager even if it is not commited so that is why the function findFragmentByTag("tag") will return fragment and will return null only if the fragment with that tag was never added to the fragment manager

getSupportFragmentManager()
   .beginTransaction()
   .setReorderingAllowed(true)
   .replace(R.id.fragment_holder, fragmentB, "tag")
   .addToBackStack(null)

above code adds the fragment to the back stack of fragment manager of host activity you can do just that and find this fragment in the fragment manager, commit is not required.

I would say it is possible, however I feel the real problem here is the design you are using. If Fragment A needs to introduce/replace Fragment B, then the correct design is to let the Activity handle the Fragment management. Fragments should not be directly adding/replacing other Fragments.

If this is all handled within the the Activity, you can easily keep a reference to the new Fragment, meaning you don't need to findFragmentByTag("tag") because you already have a reference to it when you created/replaced.

           Activity
           /      \
   Fragment A     Fragment B

Fragment A and Fragment B should not directly influence each other.

// In Activity ...
public replaceFragment() {
   Fragment fragmentB = ItemFragment.newInstance(bundle);
    
    getSupportFragmentManager()
       .beginTransaction()
       .setReorderingAllowed(true)
       .replace(R.id.fragment_holder, fragmentB, "tag")
       .addToBackStack(null)
       .commit();

    // You now have fragmentB no need to getSupportFragmentManager.findFragmentByTag("tag")
    fragmentB.doSomething();
Related