繁体   English   中英

Android,旋转设备时如何不破坏活动?

[英]Android, how to not destroy the activity when I rotate the device?

我有一个仅在纵向模式下工作的应用程序,并且我已在清单文件中对每个活动进行了更改,其方向为纵向。 但是当我旋转设备时,活动会再次重新创建。 如何不破坏活动?

对于API 12及以下版本 :添加

android:configChanges="orientation"

如果您的目标是API 13或更高版本 ,请添加“screenSize” 因为无论何时您的方向发生变化,屏幕尺寸都会发生变化,否则新设备将继续破坏您的活动。 有关使用“screenSize”的更多信息,请参阅下面的Egg的答案

android:configChanges="orientation|screenSize"

到AndroidManifest.xml中的Activity。 这样您的Activity就不会自动重启。 有关更多信息,请参阅文档

从官方文件flurin说,

注意:如果您的应用程序的目标是13级或更高级别的API(由minSdkVersion和targetSdkVersion属性声明),那么您还应该声明“screenSize”配置,因为当设备在纵向和横向之间切换时它也会发生变化。

因此,如果您的应用面向API级别13或更高级别,则应设置此配置:

android:configChanges="orientation|screenSize"

正确的解决方案是

android:configChanges="orientation|screenSize"

Android文档:

当前可用的屏幕大小已更改。 这表示当前可用大小相对于当前宽高比的变化,因此当用户在横向和纵向之间切换时会发生变化。 但是,如果您的应用程序的目标是API级别12或更低,那么您的活动始终会自行处理此配置更改(即使在Android 3.2或更高版本的设备上运行,此配置更改也不会重新启动您的活动)。*

我把它搞砸了一点,然后在Manifest文件中重新设置了我将configChanges放在应用程序级别而不是活动级别。 以下是代码在为我正确工作时的样子。

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
                  android:configChanges="orientation|screenSize|keyboardHidden">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity> 
</application> 

既然Android支持分屏(Android中的“多窗口”),你可能也想添加screenSize | smallestScreenSize | screenLayout | orientation。 因此,要处理旋转和分屏,你会在android:configChanges中想要这样的东西

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
                  android:configChanges="orientation|screenSize|keyboardHidden|smallestScreenSize|screenLayout">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity> 
</application>

在浮动图像中查看此代码。 它有最有趣的处理屏幕旋转的方式。 http://code.google.com/p/floatingimage/source/browse/#svn/trunk/floatingimage/src/dk/nindroid/rss/orientation

写在清单中:

android:configChanges="orientation|screenSize|keyboardHidden"

并在解决您的问题的活动中覆盖此:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM