Android Studio : How to keep on specific fragment while screen is rotating

If you are facing problem which the fragment is replaced while rotating the screen, here the tips on how to keep specific fragment still opened while the screen is rotating. Whenever screen rotating, the onCreate method will be executed and the first fragment will be used, so the idea is to get current fragment and pass it to fragment manager in the onCreate method.

1. Get the current fragment

FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = getSupportFragmentManager().findFragmentByTag("fragmentTag")

2. Check condition if the fragment is null or not set yet

if(fragment == null){
    //initiate initial fragment
}else{
    //use fragment
}

3. Use the current fragment

if(fragment == null){
    fragmentManager.beginTransaction().replace(R.id.containerView, new Home(),"fragmentTag").commit();
}else{
    fragmentManager.beginTransaction().replace(R.id.containerView, fragment,"fragmentTag").commit();
}

Leave a Reply

Your email address will not be published. Required fields are marked *