Search code examples
androidandroid-fragmentsfragmenttransaction

Fragment transaction show does not show my hidden fragment


This should rather be a trivial task but somehow I manage to fail in performing it.

Step 1:

Add the fragment

getSupportFragmentManager().beginTransaction().add(R.id.layFragment, Fragment1.newInstance(), "FragmentTag1").commit();

Step 2:

Hide the fragment and add another one. The second one should be visible on screen

getSupportFragmentManager().beginTransaction().hide(getSupportFragmentManager().findFragmentByTag("FragmentTag1")).commit();

getSupportFragmentManager().beginTransaction().add(R.id.layFragment, Fragment2.newInstance()),"FragmentTag2").commit();

Step 3:

The second fragment is removed and the first one is shown again

getSupportFragmentManager().beginTransaction().remove(getSupportFragmentManager().findFragmentByTag("FragmentTag2")).commit();
getSupportFragmentManager().beginTransaction().show(getSupportFragmentManager().findFragmentByTag("FragmentTag1")).commit();

Step 1and 2 are working fine. On Step 3, Fragment2 is being removed but Fragment1 is not shown again, even if it currently is hidden.

Any ideas ?


Solution

  • Instead of calling Hide & Add re Remove & Show Just Call :

    getSupportFragmentManager().beginTransaction()
        .replace(int containerViewId, Fragment fragment, String tag)
    

    Replace an existing fragment that was added to a container.