Android activity returns to an activity that triggered it instead of parent activity when you click the navigate button on the navigation bar

I have the following script:

In the Android manifest, I have three actions: ActivityA ActivityB - the parent element of ActivityA ActivityC

What I want to do is run ActivityA from ActivityC using .StartActivity () intent. Activity starts successfully. Now I want to return to the ActivityC using the back button (in the upper left corner), but since ActivityA has ActivityB as the parent (as indicated in the android manifest), the back button in the action bar returns me to ActivityB instead of the previous ActivityC. If I use the back keyboard button, I am redirected to ActivityC.

What can I do to get the same result in both cases "go back". The result I'm looking for is to redirect to the activity that started ActivityA, not the parent activity. Is it possible?

+6
source share
3 answers

You should not define ActivityB as the parent of ActivityA in the manifest. Instead, handle onOptionsItemSelected in ActivityA as follows:

public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); } return super.onOptionsItemSelected(item); } 
+12
source

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

 Intent intent = new Intent(callingActivity.this, destinationActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); 
+3
source

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 pressing the "Back" button, which will additionally save the Activity state from which you came from (tabs, scroll position).

(Credit goes to @Kise for offering this at fooobar.com/questions/956392 / ... )

+2
source

Source: https://habr.com/ru/post/956390/


All Articles