简体   繁体   中英

Android: View of landscape mode changes when I use android:configChanges=“orientation|keyboardHidden”>

I'm developing my first app, an NBA Quiz.

Here I have a Textfield with the Questions and four Buttons arranged horizontally. I then created a landscape mode and changed the structure of the Buttons to 2x2 (2 rows with 2 buttons). At first I had some problems with different screen sizes but solved it with android:layout_weight="1".

When the landscape mode looked good I had another problem: Everytime I switched to landscape mode the Quiz started over (New Question, Score was zero again). I looked for this problem here at Stackoverflow and found the following solution:

I changed the AndroidManifest.xml to

[...]
<activity android:name=".QuizActivity"
     android:configChanges="orientation|keyboardHidden">
</activity>
[...]

and in QuizActivity.java

@Override
    public void onConfigurationChanged(Configuration newConfig) {
        // TODO Auto-generated method stub
        super.onConfigurationChanged(newConfig);
    }

This solved the above problem. When I change to landscape mode the activity continues without starting anew. But now the 2x2 structure doesn't work anymore.

Here's a screenshot without the above code: landscape_mode_1

Here's a screenshot with the above code landscape_mode_2

Does anyone have an idea why the above code changes the structure of the landscape mode?

So the problem is with addition of android:configChanges="orientation|keyboardHidden" code your activity in not getting recreated on orientation changes (which solves your problem of loosing state etc.) but you lost the ability of using new layout (landscape) on orientation changes. When you define android:configChanges="keyboardHidden|orientation" in your AndroidManifest, you are telling Android: "Please don't do the default reset when the keyboard is pulled out, or the phone is rotated; I want to handle this myself."

Android destroys the Activity in orientation changes to inflate new layout (if any). So what you seeing after in landscape mode after the changes is the same layout (default/portrait) and not landscape one which is causing the button to appear horizontally instead of 2X2.

To save the state of activity across orientation changes using android:configChanges="orientation|keyboardHidden" is not recommended. Instead you should use onSavedInstanceState bundle to retain state across orientation changes as apply them to the recreated activity.

Reference onSavedInstanceState: https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

Implementation: https://www.journaldev.com/22621/android-onsaveinstancestate-onrestoreinstancestate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM