Show hide fragment in android Show hide fragment in android android android

Show hide fragment in android


Don't mess with the visibility flags of the container - FragmentTransaction.hide/show does that internally for you.

So the correct way to do this is:

FragmentManager fm = getFragmentManager();fm.beginTransaction()          .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)          .show(somefrag)          .commit();

OR if you are using android.support.v4.app.Fragment

 FragmentManager fm = getSupportFragmentManager(); fm.beginTransaction()          .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)          .show(somefrag)          .commit();


In addittion, you can do in a Fragment (for example when getting server data failed):

 getView().setVisibility(View.GONE);


Hi you do it by using this approach, all fragments will remain in the container once added initially and then we are simply revealing the desired fragment and hiding the others within the container.

// Within an activityprivate FragmentA fragmentA;private FragmentB fragmentB;private FragmentC fragmentC;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    if (savedInstanceState == null) {        fragmentA = FragmentA.newInstance("foo");        fragmentB = FragmentB.newInstance("bar");        fragmentC = FragmentC.newInstance("baz");    }}// Replace the switch methodprotected void displayFragmentA() {    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();    if (fragmentA.isAdded()) { // if the fragment is already in container        ft.show(fragmentA);    } else { // fragment needs to be added to frame container        ft.add(R.id.flContainer, fragmentA, "A");    }    // Hide fragment B    if (fragmentB.isAdded()) { ft.hide(fragmentB); }    // Hide fragment C    if (fragmentC.isAdded()) { ft.hide(fragmentC); }    // Commit changes    ft.commit();}

Please see https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments for more info. I hope I get to help anyone. Even if it this is an old question.