Search code examples
androidandroid-fragmentsfragment-backstack

How to add tag to Fragment Transaction?


I'm adding a Fragment to my Activity like this:

getSupportFragmentManager()
            .beginTransaction()              
            .add(R.id.frame_container, fragment)
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .addToBackStack(fragment.getClass().getName())
            .commit();

But when I want to find the Fragment using a FragmentManager it's returning null:

 Fragment oldFragment = (Fragment) getSupportFragmentManager().findFragmentByTag(fragment.getClass().getName());

Solution

  • You try to find it by tag, but you haven't given it any tag

    if you want to give it a tag, do it like this

    getSupportFragmentManager()
            .beginTransaction()              
            .add(R.id.frame_container, fragment, "tagABC")
            .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
            .addToBackStack(fragment.getClass().getName())
            .commit();
    

    and then you can get it with

    Fragment oldFragment = (Fragment) getSupportFragmentManager().findFragmentByTag("tagABC");
    

    BTW, you should correct your question title, the problem has nothing related to backstack.