Search code examples
androidandroid-fragmentsfragmentmanager

How to set a Tag to a Fragment in Android


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?


Solution

  • 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().