How to handle orientation change easily

故事扮演 提交于 2019-12-01 23:20:58

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">

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!