Search code examples
androidandroid-fragmentsscreen-orientationdrawerlayout

Change orientation change my fragment in DrawerLayout


I have three fragments in my DrawerLayolut:

  • Fragment A

  • Fragment B

  • Fragment C

    By default (in the init of the app) I load the FragmentA : and, if I go to the, for instance, FragmentB works well.

Problem: when I rotate my screen in the FragmentB, I come back to the FragmentA.

I don't know how to avoid this. I tried with the next code in the onCreate of the AppCompatActivity:

Fragment mFragment = null;

if(getSupportFragmentManager().findFragmentById(R.id.myframe) == null) {

   mFragment = new CalendarioFragment();
   getSupportFragmentManager().beginTransaction().add(R.id.myframe, mFragment ).commit();

} else {

   if(mFragment instanceof FragmentA){
       mFragment = (FragmentA) getSupportFragmentManager().findFragmentById(R.id.myframe);

   }else if(mFragment instanceof FragmentB){
       mFragment = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.myframe);

   }else if(mFragment instanceof FragmentC){
       mFragment = (FragmentC) getSupportFragmentManager().findFragmentById(R.id.myframe);

   }
}

But doesn't work as I expected... Could, please, somebody help me with my problem? Please, any help is welcome

I read about this other solution:

<activity android:name="CalActivity" android:configChanges="orientation|keyboardHidden"/>

But I think this isn't recomendable... (and doesn't work for me)


Solution

  • Along with <activity android:name="CalActivity" android:configChanges="orientation|keyboardHidden"/> you need to call onConfigurationChanged() in your Activity. It should look something like this:

    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        // Your code here to replace fragments correctly
    }
    

    This is the Android API guide on the subject: Handling Runtime Changes

    Though, as you said this is not recommended, a better solution would be using onSavedInstanceState and onRestoreInstanceState, like so:

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        savedInstanceState.putInt("currentFragment", 2);
    }
    
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        int fragmentNum = savedInstanceState.getInt("currentFragment");
        // Restore fragment based on fragmentNum
    }
    

    See this question for more: Saving Activity State on Android