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



所以我想暂时保存我的活动布局。我的布局是通过添加诸如ll.addView(btn);之类的儿童来创建的。但是,当我转到另一个意图并完成意图时,所有添加的按钮都会消失。我该如何预防?

您将必须实现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:android:abinationmode =''的活动中。单件程"。这是一个示例

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

最新更新