竖屏Activity跳到横屏Activity引发的混乱,Activity横竖屏切换

起因:有一个需求,竖屏Activity A跳到横屏Activity B,B操作结束后finish然后返回A,A上面重建了,之前的操作比如listview添加了item都没有了

测试条件:红米Note2一部,华为一部

测试:1.华为测试机

                打日志发现,A跳到B时,A执行了一次onCreate,B操作结束后finish然后返回A,A又执行了一次onCreate,这就是为什么A的界面被重建了。

                为了阻止A反复执行onCreate,一般的做法是

首先要在配置Activity的时候进行如下的配置:



另外需要重写Activity的onConfigurationChanged方法。实现方式如下,不需要做太多的内容:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {//横屏
        //你要执行的操作,可以不写

   } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){//竖屏
        //你要执行的操作,可以不写

    }
}

            这样写的目的是阻止Activity横竖屏切换时调用生命周期,比如onCreate

            但是经过我自己的尝试,发现并没有监听到onConfigurationChanged方法,后来发现一个外国友人的解释

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)开始,“screen size” 同时变化时的肖像和风景 取向之间的切换。因此,如果你想防止运行时重新启动,由于 方向改变时,开发API级别13或更高(如 宣布minSdkVersion和targetSdkVersion属性),你 必须包括“screen size的价值除了“定位” 价值。那就是,你必须decalare Android:configchanges =“orientation|screenSize”。然而,如果你的 应用目标API级别12或更低,那么你的活动总是 处理这种结构的变化本身(这种结构的变化 不重启你的活动,甚至在Android 3.2或更高的 装置运行时)。

 

         其实就是Android 3.2(API Level 13)开始,

android:configChanges="orientation|keyboardHidden"
    这句改成
android:configChanges="orientation|screenSize|keyboardHidden"
要多加一个
screenSize

          基本上这样就能阻止onCreate执行了,有兴趣的可以自己打日志看一下


    2.红米手机

    发现并没有出现这个问题,打了日志发现,红米手机里运行,A尽然没有切换横竖屏,这就是为什么没有问题的原因


总结,适配果然是一门大学问,一山还比一山高

            

你可能感兴趣的:(解决的问题,笔记)