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?
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);
}
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);
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With