How to set a Tag to a Fragment in Android

CBA110 picture CBA110 · May 5, 2015 · Viewed 25.5k times · Source

I've looked at all the questions on Stackoverflow but could not find a single definitive answer to this question. How do you set a Tag to a Fragment so that you can retrieve it via getFragmentManager().findFragmentByTag()? Could someone give a simple code example of how to create a tag to a Fragment?

Answer

Bartek Lipinski picture Bartek Lipinski · May 5, 2015

You can set a Tag during fragment transaction.

For example if it's a replace transaction you could do it like so:

FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
        .replace(R.id.fragment_container, mFragment, TAG)
        .commit();

If the Fragment you're using is not from Support Library, use getFragmentManager() instead of getSupportFragmentManager().