Home > Software design >  On back return to first activity and not its parent
On back return to first activity and not its parent

Time:12-15

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

  1. Start Activity B from Activity A - without calling finish()
  2. Start Activity C from Activity B - without calling finish()

Here you backpress works fine as each Activity is in stack

  1. Start Activity D from Activity C - without calling finish() /or call finish() doesn't matter in this case , as user never goes back to Activity C.
  2. OnBackpress() of Activity D, override the method (onBackPress()), and start a new Activity A with 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);

    }
  • Related