How to handle orientation change easily

2020-04-11 05:33发布

问题:

I'm working on a android application that adds every view programmaticaly. When the user turns the screen, I just want to values that are filled in to be displayed again.
Is there an easy way to let Android do this automaticaly?

My application is completely dynamic so it doens't have a predetermined layout, which makes it a lot harder.

So, how can I easily save the state of my screen?

回答1:

Everytime orientation change, android create new view and destroy the old one. You can saved your data when orientation change and re-initialize when the new view is created

Use onConfigurationChanged method of activity to detect Orientation Change

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();
    }
  }

Don't forget to edit the appropriate element in your AndroidManifest.XML like this to include the android:configChanges

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">


回答2:

For an expanded explanation of Hein's correct answer see my previous post:

https://stackoverflow.com/a/57239493/5696328