Android横竖屏切换

移动开发 Android
在Android 2.3平台上,我们可以需要设置界面的横竖屏显示时,可以在AndroidManifest.xml中,同时在Activity中覆写onConfigurationChanged方法,通过设置,当前Activity在横竖屏切换的时候,便不会重新走Activity的生命周期,而是直接执行onConfigurationChanged()方法里的内容。在Android 4.0上,API level 13以后Android做了修改,横竖屏切换时屏幕尺寸改变了。

Android 2.3以前的横竖屏切换:

在Android 2.3平台上,我们可以需要设置界面的横竖屏显示时,可以在AndroidManifest.xml中,对Activity的属性添加以下代码:

  1. Android:configChanges="orientation" 

同时在Activity中覆写onConfigurationChanged方法

  1. @Override 
  2. public void onConfigurationChanged(Configuration newConfig) { 
  3. super.onConfigurationChanged(newConfig); 
  4. Log.i("TAG","I'm Android 2.3"); 

通过设置,当前Activity在横竖屏切换的时候,便不会重新走Activity的生命周期,而是直接执行onConfigurationChanged()方法里的内容。

Android 4.0以后的横竖屏切换:

当我们在Android 4.0上像之前那样设置横竖屏时,会发现竟然没有效果,Activity依然走自己的生命周期,这是因为在API level 13以后Android做了修改了,SDK描述如下:

 

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).

 

也就是说在Android 3.2(API level 13)以后,当设备横竖屏切换时屏幕尺寸也改变了。因此,如果你想在API Level 13或者 更高的环境下,像以前那样阻止设备的横竖屏切换,你需要在orientation后加上screenSize。也就说你要像这样声明:android:configChanges="orientation|screenSize"。

也就是说我们现在要在AndroidManifest.xml中的Activity加入以下属性:

Android:configChanges="orientation|screenSize"

责任编辑:闫佳明 来源: oschina
相关推荐

2010-01-25 15:23:12

Android横竖屏切

2011-07-29 10:21:03

iPad 横竖屏 切换

2011-06-08 15:05:43

J2ME

2013-08-21 11:15:54

iOS横竖屏方案

2017-07-25 09:55:10

iOS横竖屏旋转

2012-05-22 14:26:15

XNA 横竖屏设置

2016-09-18 10:51:01

JavascriptHtml5移动应用

2021-06-28 14:41:36

鸿蒙HarmonyOS应用

2012-07-16 10:09:39

Windows 7操作系统

2023-06-29 08:41:34

Android“短暂”模式

2009-07-07 08:44:52

微软Windows 7新功能

2010-01-28 17:12:45

Android闪屏

2011-09-07 10:44:05

Android Wid

2013-07-29 05:04:19

Cocos2dx横屏竖

2010-09-10 10:09:26

Android

2017-01-11 18:36:04

Android矩形区域截屏移动开发

2012-02-28 14:07:17

Android触摸屏手势识别

2014-04-29 13:58:11

OpenGL ESAndroid响应触屏事件

2015-03-24 10:51:46

Android锁屏

2020-08-28 10:01:08

AndroidPC手机屏幕
点赞
收藏

51CTO技术栈公众号