How to change layout when rotate?

Home / Uncategorized / How to change layout when rotate?

Question:
I have an xml in layout-normal, layout-large and layout-land. What I’m trying to do is to use the provided xml in specific orientation.

I already search for it here and this are what I’ve already tried.

1) I used different layout name but same ids in it and override onConfigurationChanged and set the layout there. Here’s my code
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);

if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
{
setContentView(R.layout.activity_login2);
}
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
{
setContentView(R.layout.activity_login );
}
}

It does changed but when the screen rotates the inputed data in the EditText is gone. I tried to use onSaveInstanceState to save the instance but still the same. It looks like it destroys the activity and create a new one where all my widget that is initialized in onCreate is gone.

2) Then I found layout-land and just put the landscape layout there with same layout name like in layout-normal and layout-large example is

res/layout-land -> activity_login.xml

res/layout-normal-> activity_login.xml

res/layout-large-> activity_login.xml

and removes the onConfigurationChanged on the code but still doesn’t work.

In my AndroidManifest in LoginActivity I put





Is there anyway to change the layout when screen is rotated? Thank you in advance.


Answer:
The "screen size" qualifier has higher precedence than the "orientation" qualifier. https://developer.android.com/guide/topics/resources/providing-resources.html#AlternativeResources

Android supports several configuration qualifiers and you can add multiple qualifiers to one directory name, by separating each qualifier with a dash. Table 2 lists the valid configuration qualifiers, in order of precedence

Suppose you have these files:res/
layout-normal/
layout.xml
layout-land/
layout.xml

If you have a normal screen size device, it won’t matter whether you use portrait or landscape. layout-normal will always be chosen over layout-land.

You can solve this two different ways.

First, you could put your "default" layout in the plain layout directory (instead of layout-normal). So your files would be
res/
layout/
layout.xml
layout-land/
layout.xml

Second, you could combine qualifiers in order to make it obvious that you’re differentiating between portrait and landscape. So your files would be
res/
layout-normal/
layout.xml
layout-normal-land/
layout.xml
Read more

Leave a Reply

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