簡體   English   中英

重新啟動活動,而不是重新創建[Android]

[英]Restart activity instead reCreate [Android]

我的活動A,B,C有以下情況:A-> B-> C-> A

在最后一步(C-> A)中,我想覆蓋C的onBackPressed,以便它重新啟動活動A(而不重新創建活動)。 我在下面嘗試了代碼,但仍然調用A的onCreate()。 我應該添加哪個標志?

public void onBackPressed() {

    Intent intent=new Intent(C.this, A.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);

}

這是刷新活動的最佳方法:

public void refresh() {
   Intent intent = getIntent();
   overridePendingTransition(0, 0); 
   intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
   finish(); 
   overridePendingTransition(0, 0); 
   startActivity(intent); 
   }

將會調用 OnCreate,這是正確的行為 ,以下是來自Google文檔的信息

在先前銷毀活動之后重新創建活動之后,可以從捆綁包中恢復系統通過活動的保存狀態。 onCreate()和onRestoreInstanceState()回調方法都接收包含實例狀態信息的同一個Bundle。

由於onCreate()方法是系統是創建活動的新實例還是重新創建活動的實例而調用的,因此在嘗試讀取狀態Bundle之前,必須檢查其狀態是否為null。 如果為空,則系統將創建活動的新實例,而不是還原先前被破壞的活動。

但這是否正確處理並不重要,例如:

@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
    }
    ...
}
public void onBackPressed() {

    Intent intent=new Intent(C.this, A.class);
    // remove below Flag and while going from A dont call finish();
    //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);

}

因此,您想確定活動A與切換到活動B之前的狀態相同,對嗎?

您是否嘗試過使用onSaveInstanceState() / onRestoreInstanceState() (分別為onCreate(Bundle savedInstanceState) )回調,如https://developer.android.com/training/basics/activity-lifecycle/recreating.html中所述 例如此處: https//stackoverflow.com/a/151940/3540885

我不確定您想要的方式是否可行。 通常,最好讓Android處理生命周期本身。 只要在系統感覺要破壞您的活動時就保存重要的內容-這樣您就可以再次使用上一個狀態重新創建它...

編輯:這是很久以前,因為我上次搞錯了多個活動。 您是否考慮過使用片段而不是多個活動? 一旦了解了片段的概念,我便開始僅使用一個父活動並替換了片段。 因此,您所有的“重物”都可以在父活動中實例化一次,並由需要它的片段進行訪問。 這可能是替代解決方案,恕我直言,值得思考。

我喜歡Stanojkovic答案,並且可以使用意圖將其保存以保存數據。

 public void refresh() {
   Intent intent = getIntent();
   intent.putExtra("extra_id",details);   
   overridePendingTransition(0, 0);
   intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); 
   finish(); 
   overridePendingTransition(0, 0); 
   startActivity(intent); 
   }

並將其放入onCreate

details=getIntent().getStringExtra("extra_id")

暫無
暫無

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

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