应用横竖屏切换造成、UI改变 、数据丢失的处理 onConfigurationChanged

版权声明:转发请标明原著 https://blog.csdn.net/weixin_39460667/article/details/82979814

我们直接进入主题

应该如何来解决这个问题呢

步骤一 权限声明:

<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"></uses-permission>

步骤二 添加要防止的事件类型:如下

       <activity
            android:name=".Fragment.ViewPagerFragment"
            android:configChanges="keyboard|screenSize|orientation|layoutDirection">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

步骤三:重写Activity中的onConfigurationChanged方法。

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (this.getResources().getConfiguration().orientation ==
                Configuration.ORIENTATION_LANDSCAPE) {
            //横屏
        } else if (this.getResources().getConfiguration().orientation ==
                Configuration.ORIENTATION_PORTRAIT) {
            //竖屏
        }
        super.onConfigurationChanged(newConfig);
    }

注意:

自从Android 3.2(API 13),在设置Activity的android:configChanges="orientation|keyboardHidden"后,还是一样会重新调用各个生命周期的。

因为screen size也开始跟着设备的横竖切换而改变。

所以,在AndroidManifest.xml里设置的MiniSdkVersion和 TargetSdkVersion属性大于等于13的情况下,如果你想阻止程序在运行时重新加载Activity,除了设置"orientation"

你还必须设置"ScreenSize"。

解决方法:

AndroidManifest.xml中设置android:configChanges="orientation|screenSize“

禁止横竖屏

在AndroidManifest.xml的activity(需要禁止转向的activity)配置中加入 android:screenOrientation=”landscape”属性即可(landscape是横向,portrait是纵向)。

猜你喜欢

转载自blog.csdn.net/weixin_39460667/article/details/82979814
今日推荐