This methods allow you to retrieve a previously added fragment instance without needing to keep a reference to that fragment's instance. The difference between the two lie on the way they track it, if its either with a given TAG, that you previously assigned to the fragment transaction when it was added, or just by retrieving the last added fragment in the given container. Let's go through both methods:
findFragmentByTag:
This method allows you to retrieve the instance of a previously added fragment with the given tag regardless of the container it was added to. This is done the following way:
Let's first add a fragment with a TAG:
MyFragment fragment = new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.place_holder,fragment,"myFragmentTag");
fragmentTransaction.commit();
And then to retrieve the fragment's instance:
fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag("myFragmentTag");
if(fragment != null){
// ok, we got the fragment instance, but should we manipulate its view?
}
If fragment
is not null, it means you got the instance referring to that fragment TAG. Keep in mind that with this method, even tho you get the instance, doesn't mean the fragment is visible or added to the container, which means you should make an extra check if you mean to handle something in it's view, with:
if(fragment != null && fragment.isAdded()){
// you are good to go, do your logic
}
findFragmentById:
In this method you are going to get the instance of the last added fragment to the given container. So let's pretend we add a fragment to the container without tag (notice that you can also give it a tag and retrieve it this way):
MyFragment fragment = new MyFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragment_container,fragment);
fragmentTransaction.commit();
And then to retrieve it's instance you use the container id:
fragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if(fragment != null){
// you are good to go, do your logic
}
At this moment, since we used findFragmentById
we know it is the visible fragment of the given container so you don't need to check if it is added to a container.