2017-08-31 72 views
-1

所以我想暫時保存我的活動佈局。我的佈局是在LinearLayout中創建的,通過添加像ll.addView(btn); 這樣的子項但是當我轉到另一個Intent時,並且該Intent完成後,所有添加的按鈕消失。我怎樣才能防止這一點?Android保存活動動態創建佈局onPause

+0

爲什麼ü想要做這樣嗎? – Rahul

+0

從服務收到數據。當用戶選擇數據 - >活動顯示他們 - >回數據選擇 – Berrigan

+1

儘管所有的答案在這裏,你應該檢查,爲什麼你的活動重新創建。 – JacksOnF1re

回答

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方法恢復佈局的動態視圖。你決定什麼是最適合你的。

+0

'onCreate'不是'onRestoreInstanceState'的替代方法。 –

+0

@BirendraSingh它是。從文檔:「onCreate()和onRestoreInstanceState()回調方法都會收到包含實例狀態信息的相同Bundle。」 https://developer.android.com/guide/components/activities/activity-lifecycle.html#saras – 2017-08-31 12:21:58

+0

來自同一頁面**不是在'onCreate()'期間恢復狀態,你可以選擇實現'onRestoreInstanceState() ',*系統在'onStart()'方法之後調用***。如果有人實現了'onStart()'來初始化一些狀態變量,邏輯就會中斷。 –

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

這將爲活動創建另一個啓動器,據我所知 – Berrigan

+0

不,我從我的項目中複製此代碼段,其中啓動模式用於我的MainActivity(這也是啓動器活動)。我正在解釋的是android:launchMode =「singleTask」 –

+0

這裏不工作。 – Berrigan

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

}