Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android activity go back to activity that started it instead of parent activity when pressing navigation bar back button

I have the following scenario:

In android manifest I have three activities: ActivityA ActivityB - parent of ActivityA ActivityC

What I want to do is start ActivityA from ActivityC using intent.StartActivity(). The activity is started successfully. Now I want to go back to ActivityC using actionbar's back button (upper left corner), but since ActivityA has ActivityB as parent (as declared in android manifest) the actionbar back button takes me to ActivityB instead of previous ActivityC. If I use the back keyboard button, I get redirected to the ActivityC.

What can I do to get the same result in both "navigate back" cases. The result I'm seeking is to get redirected to the activity that started the ActivityA and not it's parent activity. Is it possible?

like image 204
Radian Avatar asked Oct 21 '13 08:10

Radian


3 Answers

You should not define ActivityB as parent for ActivityA in manifest. Instead, handle onOptionsItemSelected in ActivityA like this:

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            finish();
        }
    return super.onOptionsItemSelected(item);
    }
like image 79
Juozas Kontvainis Avatar answered Nov 14 '22 22:11

Juozas Kontvainis


When you call startActivity(), do it like that:

Intent intent = new Intent(callingActivity.this, destinationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
like image 23
Yurii Kyrylchuk Avatar answered Nov 14 '22 21:11

Yurii Kyrylchuk


Try the following:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            return true;  
    }

    return super.onOptionsItemSelected(item);
}

This will emulate a back button press, which will additionally preserve the state of the Activity you came from (tabs, scroll position).

(Credit goes to @Kise for suggesting this in https://stackoverflow.com/a/31331757/2703209)

like image 26
user149408 Avatar answered Nov 14 '22 21:11

user149408