aroSuv
aroSuv

Reputation: 137

How can I use different layout in android orientation change

I want to use a separate layout for my fragment on landscape view , hence I have created a separate layout for landscape view . But the problem is when I rotate the screen onConfigurationChanged , onDestroyView onDestroy called sequentially . And it backs to previous fragment . I can prevent it by using android:configChanges="orientation|screenSize" on my activity . But in this case , the view remains same it doesn't use my separate layout , it is just stretched to fill the screen . Is there any way so that I can use separate layout while using android:configChanges="orientation|screenSize" ?

Upvotes: 1

Views: 8488

Answers (3)

Mustansar Saeed
Mustansar Saeed

Reputation: 2790

Please remove andorid:configChanges from manifest. Its purpose is that you yourself is handling configuration changes. Remove it and android will automatically pick the right layout file.

Hope this helps.

Upvotes: 0

Vyacheslav
Vyacheslav

Reputation: 27221

To use different layouts use different resourse folders: That is, use layout folder for portrait and layout-lang for landscape mode.

you can use getResources().getConfiguration().orientation to detect orientation, then load XML you like something like this:

@Override
    protected void onCreate(Bundle savedInstanceState) {
switch (getResources().getConfiguration().orientation) {
                      case Configuration.ORIENTATION_PORTRAIT:
setContentView(R.layout.aportrait);
                         break;
                      case Configuration.ORIENTATION_LANDSCAPE:
setContentView(R.layout.alandscape);
                         break;
                    }

/////..............
}

Upvotes: 3

Pankaj Nimgade
Pankaj Nimgade

Reputation: 4549

your issue is quite generic,

If you disable the orientation and make it a constant to portrait/landscape, the changes in orientation of the device (phone) will not force the activity to be re-created. so even though you have separate layout for fragment it will not be loaded,

and if you make orientation of activity depending on the orientation change to the device (Phone) it will re-create the activity due to which you activity will initialize everything as result you are getting the first fragment while rotating the screen.

to deal with it, what you can do is use savedInstanceState(Bundle) while recreating the activity,

save the current fragment you have loaded and mention that to your savedInstanceState(Bundle) and after re-creating the activity when the orientation is changed, read the savedInstanceState and you will know which fragment to load

Upvotes: 2

Related Questions