onConfigurationChanged problems

橙三吉。 提交于 2019-12-11 16:26:14

问题


I need to change layout of my Android (4.1 API 16) application when orientation is changed.

 @Override
    public void onConfigurationChanged(Configuration newConfig) {
      super.onConfigurationChanged(newConfig);
      setContentView(R.layout.main_2);
      System.out.println("Orientation changed!");
    }

Also I have added the next line to manifest file

android:configChanges="orientation"

I use Ctrl+F11 to change orientation. My screen rotates but layout stays the same and nothing is printed in LogCat. Feels like onConfigChanged event doesn't occur.

Where is my mistake?

Thank you.


回答1:


Try using android:configChanges="orientation|keyboardHidden|screenSize"

Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must decalare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).

Source : Documentation

Hence, also add "|screenSize" to configChanges if your application targets API 13 and above.




回答2:


Lets say your portrait orientation layout file is in layout/my_layout.xml

Place the layout you want to be used in the landscape mode in layout-land folder with the same layout file name. i.e. layout-land/my_layout.xml

Do not add android:configChanges="orientation" to the the manifest for that activity.

You do not need to explicitly change the layout. You do not need to override the onConfigurationChanged(Configuration newConfig) function




回答3:


try this one....

android:configChanges="orientation|keyboardHidden|screenSize"


来源:https://stackoverflow.com/questions/12226652/onconfigurationchanged-problems

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