Search code examples
androidandroid-intentkotlinflagsback-stack

Return to Specific Activity in 2 different Condition when Back button Pressed Kotlin


Activity A,B,C,D .first path is A->C->D .when back button Pressed from D ,it will go like D->C->A. But My requirement is D->A. in same App, I have another condition .second path is A->B->C->D .when back button pressed from D,it will happen like D->C->B->A.But My Requirement is D->A. How to easily Accommodate both requirement in my App ? but note that when click back from C then it should go to B.


Solution

  • Override onBackPressed() in D like this:

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(this, A.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
        finish();
    }
    

    This will remove all activities between D and A from the stack and return to the existing instance of A.

    NOTE: This is Java, not Kotlin, but you should be able to figure out how to Kotlinize the code ;-)