如何在横竖屏切换时Activity内容不变

众所周知,默认情况下,从水平变为垂直,Android的操作过程为关闭Activity,再在当前方向打开此Activity。此过程一般而言没有什么不妥,只是会带来一个问题:用户数据丢失,也就是说,Activity 重启,必然使得内容初始化。补救措施是在变换方向时保存当前内容,如webview的url等。

这种做法当然不够好玩。

正确的做法是,配置Activity的变化状态(这么说可能不大准确。),在AndroidManifest.xml中,对于每一个Activity的配置,有一个属性,android:configChanges=""。这个属性的官方解释是

通过设置这个属性可以使Activity捕捉设备状态变化,以下是可以被识别的内容:  

CONFIG_FONT_SCALE
CONFIG_MCC
CONFIG_MNC
CONFIG_LOCALE
CONFIG_TOUCHSCREEN
CONFIG_KEYBOARD
CONFIG_NAVIGATION

CONFIG_ORIENTATION

那么,如下配置则可以完成我们想要的结果:

代码截图

补充:

每一个config的具体说明:

Value Description
mcc The IMSI mobile country code (MCC) has changed — that is, a SIM hasbeen detected and updated the MCC.移动国家号码,由三位数字组成,每个国家都有自己独立的MCC,可以识别手机用户所属国家。
mnc The IMSI mobile network code (MNC) has changed — that is, a SIM hasbeen detected and updated the MNC.移动网号,在一个国家或者地区中,用于区分手机用户的服务商。
locale The locale has changed — for example, the user has selected a new language that text should be displayed in.用户所在地区发生变化。
touchscreen The touchscreen has changed. (This should never normally happen.)
keyboard The keyboard type has changed — for example, the user has plugged in an external keyboard.键盘模式发生变化,例如:用户接入外部键盘输入。
keyboardHidden The keyboard accessibility has changed — for example, the user has slid the keyboard out to expose it.用户打开手机硬件键盘
navigation The navigation type has changed. (This should never normally happen.)
orientation The screen orientation has changed — that is, the user has rotated the device.设备旋转,横向显示和竖向显示模式切换。
fontScale The font scaling factor has changed — that is, the user has selected a new global font size.全局字体大小缩放发生改变
(部分内容引用: http://hiapk.com/thread-6199-1-1.html

你可能感兴趣的:(android,Activity,屏幕旋转,水平,竖直)