[英]Android Clear Middle Activities
I have 5 Activities, 我有5个活动,
A - Base Activity A-基本活动
B,C,D - Normal Activities B,C,D-正常活动
E - Final Activity E-最终活动
ABCDE ABCDE
I navigate from A to B to C to D, D takes me to E. I want behaviour : if I press back button on D it should take me to C , back button from C should take me to B down to A. But if I have moved to Activity E from D, I want the back button from E it should take me to A skipping B,C and D. 我从A导航到B,再到C导航到D,D带我进入E。我想要的行为是:如果我按D上的后退按钮,它将带我到C,而从C的后退按钮应该将我带到B到A。我已经从D移到了活动E,我希望从E移回按钮,这应该使我跳到A,跳过B,C和D。
In E
: 在E
:
@Override
public void onBackPressed() {
Intent intent = new Intent(this, ActivityA.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
This will go back to A
, finishing B
, C
, D
and E
. 这将返回到A
,完成B
, C
, D
和E
Using FLAG_ACTIVITY_SINGLE_TOP
will ensure that you return to the existing instance of A
. 使用FLAG_ACTIVITY_SINGLE_TOP
将确保您返回到A
的现有实例。 If you want to also finish the existing instance of A
and create a new one to return to, simply remove FLAG_ACTIVITY_SINGLE_TOP
. 如果您还想完成A
的现有实例并创建要返回的新实例,只需删除FLAG_ACTIVITY_SINGLE_TOP
。
You can use a static variable to track which activity you're coming from. 您可以使用静态变量来跟踪您来自哪个活动。 Then override onBackPressed to check that variable and move to the appropriate activity. 然后覆盖onBackPressed以检查该变量并移至适当的活动。 Something like: 就像是:
public static Boolean skipActivities = false;
Then when you start activity E from D set it to true. 然后,当您从D启动活动E时,将其设置为true。 For your activity E: 对于您的活动E:
@Override
public void onBackPressed() {
if (skipActivities){
//start activity A, skipActivities should be reset to false also
} else {
super.onBackPressed();
}
}
you can "group" you activities, by using affinity
. 您可以使用affinity
活动进行“分组”。 So in Manifest file add android:taskAffinity="activity.normal"
to activities B,C,D,E. 因此,在清单文件中,将android:taskAffinity="activity.normal"
到活动B,C,D,E。 And now you'll be able to finish all this group in any of this activities by calling finishAffinity()
(instead of usual finish()
) in your case you can just add to E activity: 现在,您可以通过调用finishAffinity()
(而不是通常的finish()
)来完成所有此活动中的所有组,您可以将其添加到E活动中:
@Override
public void onBackPressed() {
finishAffinity();
super.onBackPressed();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.