I have an activity A that once the user presses a button it opens activity B.
I do that using:
startActivity(intent)
finish()
The user in Activity B has the option to click on an item and navigate to activity C or press the back button.
Problem:
When pressing the back button, I don't go to Activity A but to its parent.
How can I make sure that on back navigation I go to Activity A, while if the user clicks on an item in Activity B they end up in Activity C?
CodePudding user response:
Suppose you have 4 Activities : A , B , C and D.
User goes from A -> B -> C , i.e. from Activity C user goes to B onBackPress and then A.
But if user goes A -> B -> C -> D, here onBackPress user goes to Activity A.
To implement this you can follow this approach
- Start
Activity BfromActivity A- without callingfinish() - Start
Activity CfromActivity B- without callingfinish()
Here you backpress works fine as each Activity is in stack
- Start
Activity DfromActivity C- without callingfinish()/or callfinish()doesn't matter in this case , as user never goes back toActivity C. - OnBackpress() of
Activity D, override the method (onBackPress()), and start a newActivity Awith clear the backstack (intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);)
Or for Activity A you make play with launch modes, Make Activity A SingleTask so when you again start Activity A from Activity D, same instance of Activity A will be called clearing all tasks(activites) at top
CodePudding user response:
Just add
startActivity(intent)
Don't call Finish() While redirect to Activity B. It will resolve your back navigation problem.
CodePudding user response:
override onBackPressed() method
@Override
public void onBackPressed() {
super.onBackPressed();
//Set your intent
Intent intent = new Intent(currentAct.class,Activity A);
startActivity(intent);
}
