1

I searched everywhere in the site and found no answer. So far I managed to keep important states of my App when orientation changes but now I want to have separate fragments for each orientation:

If (Portrait Mode) => attach fragment portrait to activity

if (Landscape Mode) => attach fragment landscape to activity

I don't want just two separate layouts, but two different fragments (this is because I want to add some functionality that's "impossible" to achieve in portrait mode). How can I achieve this?

Miguel Duran Diaz
  • 302
  • 1
  • 3
  • 12

2 Answers2

1

We suggest checking your orientation in onResume() method of your activity like bellow.

@Override
    protected void onResume() {
        super.onResume();
        int mOrientation = this.getResources().getConfiguration().orientation;
        if (mOrientation == Configuration.ORIENTATION_PORTRAIT) {
            // code for portrait mode
            //Add your Portarait fragment
        } else {
            // code for landscape mode
            // Add your landscape fragment
        }
    }
Dhaval Solanki
  • 4,589
  • 1
  • 23
  • 39
0

You can check for orientation changes in onConfigurationChanged of the activity that you're attaching your fragments.

So, what you need to do is,

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        //set the fragment for landscape mode
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
         //Set the fragment for portrait mode
    }
}

Also, don't forget to add

android:configChanges="orientation|screenSize" in the activity tag in your manifest file that you're handling configuration changes.

Vedprakash Wagh
  • 3,595
  • 3
  • 12
  • 33
  • It works! However now I loss my "state" (which is actually just an array) is there an easy way to still mantain my state? As far as I understand, when I change orientation, onConfigurationChanged is called and there I'm inflating the appropiate fragment but.. here there is no way to keep the state or is there? – Miguel Duran Diaz Jun 06 '19 at 16:25
  • 1
    Check this out https://stackoverflow.com/questions/15313598/once-for-all-how-to-correctly-save-instance-state-of-fragments-in-back-stack – Vedprakash Wagh Jun 06 '19 at 16:30