簡體   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