Android保存活动在onPause中动态创建布局

时间:2017-08-31 11:43:45

标签: android android-layout android-intent android-activity

所以我想暂时保存我的Activity布局。我的布局是通过添加像ll.addView(btn);这样的子项在LinearLayout中创建的 但是当我去另一个Intent,并且Intent完成时,所有添加的按钮都会消失。我该如何防止这种情况?

3 个答案:

答案 0 :(得分:1)

您必须实施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方法恢复布局的动态视图。你决定什么是最适合你的。

答案 1 :(得分:1)

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); 
    }

}

答案 2 :(得分:0)

要防止每次使用Intent()操作调用Activity时内容始终更新,请转到Manifest文件并将标记添加到名为`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>