Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
618 views
in Technique[技术] by (71.8m points)

java - Activity reloads when orientation changes in Android

When my main activity starts after the splash screen it parses 4 big XML files. This takes a few seconds and I'm able to hide this in the time the splash screen shows at startup.

But when the screen orientation changes or when I go back to the main activity after a sub-activity it parses again and thus fore my app 'hangs' for a few seconds and it doesn't respond or anything in that time.

I understand this is normal behaviour in Android, but isn't there a way to avoid this?

I read something about savedinstancestate, but I can't seem to understand the docs..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

add this code in your android manifest file in every activity node if you're targeting API level 12 or less.

android:configChanges="orientation|keyboardHidden"

For level 13 and onwards you also have to include "screensize", i.e.:

    android:configChanges="orientation|keyboardHidden|screenSize"

now paste this code in your every activity's java classes.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
    // Checks whether a hardware keyboard is available
    if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_NO) {
        Toast.makeText(this, "keyboard visible", Toast.LENGTH_SHORT).show();
    } else if (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES) {
        Toast.makeText(this, "keyboard hidden", Toast.LENGTH_SHORT).show();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...