Can I force the Android Back button to go two steps back in the Activity stack?
I know that I can override the onKeyDown
method, but I want Back to d开发者_StackOverflow中文版o it's thing, just twice!
FirstActivity
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
startActivity(intent);
SecondActivity
int REQUEST_CODE = 123
Intent intent = new Intent(SecondActivity.this, ThirdActivity.class);
startActivityForResult(intent, REQUEST_CODE);
(to make this pedagogic there is more code for this activity below)
ThirdActivity
@Override
public void onBackPressed() {
// Semi ugly way of supporting that back button takes us back two activites instead of the usual one.
setResultOkSoSecondActivityWontBeShown();
finish();
}
private void setResultOkSoSecondActivityWontBeShown() {
Intent intent = new Intent();
if (getParent() == null) {
setResult(Activity.RESULT_OK, intent);
} else {
getParent().setResult(Activity.RESULT_OK, intent);
}
}
SecondActivity (again)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 123) {
if (resultCode == RESULT_OK) {
finish();
}
}
}
I am thinking of it this way:
A -> B -> C
A, B, C activities.
You can't do a back twice since the first onKeyDown()
will be executed in C and the second one should be executed in B.
I don't know why you are trying to do, but here are some options.
Using the
android:noHistory
tag:Perhaps your C activity is doing something that doesn't need a view and that's why you want to back twice.
Using an intent. Something like:
Intent intent = new Intent(C.this, A.class); startActivity(intent);
Using the
finishActivityFromChild()
. I have never try it, but it looks like you can use it to decide what to do on B depending of how C ended.
|*| Going back one screen or end activity :
finish();
|*| Going back more than one screen :
You can go back to which ever screen you need using intent and use flags to prevent going back to same screen :
Intent gotoScreenVar = new Intent(goFromScreenCls.this, goToScreenCls.class);
gotoScreenVar.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(gotoScreenVar);
精彩评论