簡體   English   中英

Android保存活動在onPause中動態創建的布局

[英]Android save activity dynamically created layout in onPause

所以我想暫時保存我的活動布局。 通過添加ll.addView(btn);類的子ll.addView(btn); ,在LinearLayout中創建我的布局ll.addView(btn); 但是,當我轉到另一個Intent並且該Intent完成時,所有添加的按鈕都消失了。 我該如何預防?

您將必須實現onSaveInstanceState(Bundle)onRestoreInstanceState(Bundle)

onSaveInstanceState您將在包中動態創建視圖所需的信息存儲在其中。

onRestoreInstanceState您可以從捆綁軟件中獲取此信息,然后重新創建動態布局。

就像是:

@Override
public void onSaveInstanceState(Bundle bundle) {
  bundle.putString("key", "value"); // use the appropriate 'put' method
  // store as much info as you need
  super.onSaveInstanceState(bundle);
}

@Override
public void onRestoreInstanceState(Bundle bundle) {
  super.onRestoreInstanceState(bundle);
  bundle.getString("key"); // again, use the appropriate 'get' method.
  // get your stuff
  // add views dynamically
}

或者,您可以從onCreate方法(而不是onRestoreInstanceState方法)還原布局的動態視圖。 您可以決定最適合自己的。

You can make use of onSaveInstanceState to save the view and 
onRestoreInstanceState to retrieve the saved view.

private String someVarB;

...

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putString("btn_added", "true");
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    someVarB = savedInstanceState.getString("btn_added");

    if(someVarB.equalsIgnoreCase(true))
    {
         ll.addView(btn); 
    }

}

為了防止每次使用Intent()操作調用活動的內容時總是更新該內容,請轉到清單文件,然后將標簽添加到名為“ android:launchMode =“ singleTask”的活動中。 這是一個例子

<activity
        android:name=".MainActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/app_name"
        android:launchMode="singleTask"
        android:screenOrientation="portrait"
        android:theme="@style/AppTheme.TranscluscentBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

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

暫無
暫無

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

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