2015-11-23 91 views
4

我有一個活動的層次和我有一個按鈕,讓我從一個活動d到活動B.管理android的堆棧中

image

的事情是,會從d到B會離開C對所以如果我做A-> C-> D-> B,然後按回它會把我送到C,而不是A(這是我想要的)。

當我點擊B按鈕或者是否有某種解決方法時,是否有刪除C的方法?

+0

您可以用片段做到這一點,而不是,FragmentManager讓您管理堆棧。同時查看父級活動:http://developer.android.com/training/implementing-navigation/temporal.html –

回答

0

考慮使用A作爲調度程序。當你想從D推出B並在此過程完成C,爲此在D

// Launch A (our dispatcher) 
Intent intent = new Intent(this, A.class); 
// Setting CLEAR_TOP ensures that all other activities on top of A will be finished 
// and setting SINGLE_TOP ensures that a new instance of A will not 
// be created (the existing instance will be reused and onNewIntent() will be called) 
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP); 
// Add an extra telling A that it should launch B 
intent.putExtra("startB", true); 
startActivity(intent); 

A.onNewIntent()做到這一點:

@Override 
protected void onNewIntent(Intent intent) { 
    if (intent.hasExtra("startB")) { 
     // Need to start B from here 
     startActivity(new Intent(this, B.class)); 
    } 
} 
+0

謝謝,工作得很好。這種方法如何工作效率明智?在運行intent之前它是否一直運行到onResume()? –

+1

可能。在這種情況下我不記得它是否調用了'onResume()',因爲另一個Activity將被啓動。它可能。你可以添加一些日誌來看看你自己。但我認爲這不是一個值得擔心的效率問題。 –

0

我不知道你打電話給B,C和D的具體細節,或者是什麼數據傳過來的,但是如果你願意,你可以打電話給D來關閉C。

在C,開始d時,你可以這樣做:

Intent intent = new Intent(this, D.class); 
startActivity(intent); 
finish(); 

終點開始D.

後再次將關閉C,沒有太多的信息,這只是在黑暗中拍攝,雖然。

+0

A,B和C可以通過按鈕欄從任何其他活動中調用,而D只能從C. 我不想完成C,因爲我打開D,因爲按下後退按鈕會讓我回到A. –

+0

這種方法是行不通的。如果你想從D轉到B,那麼你可能需要使用帶有片段管理器的片段,或者創建自己的堆棧管理器。 – TooManyEduardos