簡體   English   中英

如何處理螢幕方向變更

[英]How to handle screen orientation change

我正在嘗試為我的Android應用程序處理屏幕方向更改,但沒有成功。 這是我的清單:

  <activity
        android:name="fr.ups.l3info.l3info_catchgameactivity.CatchGameActivity"
        android:label="@string/app_name" 
        android:screenOrientation="user"
        android:configChanges="orientation|keyboardHidden" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

我在活動類中添加了此功能:

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

但是,當我更改屏幕方向時,將重新創建該應用程序,並且永遠不會執行此功能。 我做錯了什么? 謝謝你的幫助。

在清單清單android:configChanges="keyboardHidden|orientation|screenSize|layoutDirection"使用此android:configChanges="keyboardHidden|orientation|screenSize|layoutDirection"

您可能想了解有關活動生命周期的更多信息。 您可以在此處找到更多信息( http://developer.android.com/training/basics/activity-lifecycle/index.html

但更重要的是要熟悉您的活動狀態

您要查找的方法不是onConfigurationChanged(Configuration newConfig) ,而是onSaveInstanceState(Bundle savedInstanceState)

現在,在您的OnCreate()方法中,您需要檢查是否已經保存了某些狀態,然后重新創建該狀態。

在此鏈接上有一個很好的解釋: 使用“保存實例狀態”保存Android活動狀態

但基本上您需要做的是:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

然后考慮到這一點:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...
}

STATE_SCORESTATE_LEVEL是一些public static final String值,用於以某種方式標記要保存的內容。

例如,如果您具有EditText視圖,然后鍵入內容,然后旋轉屏幕,則該值將丟失。 但是,在onSaveInstanceState()方法中,應使用該Bundle參數並將EditText視圖的值作為String放置。

保存該內容后,現在您可以在onCreate()方法中獲取該值,並為其設置EditText視圖的值。

希望這可以幫助 :)

如果您嘗試在方向更改時為您的應用程序定義“不同的布局”,只需定義一個新的布局,使其名稱與其他布局相同 ,然后將其置於res/layout-land

這樣,當您的應用程序重新創建自己並在onCreate函數中調用setContentView(layout_name) ,它將調用下res/layout-land而不是下res/layout

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM