Search code examples
androidandroid-activityback

Change Back Button Behaviour - Android


I have an application . The flow is -
Splash Screen ---> Home Screen ---> Item List Screen ---> Item Details Screen

In my application i have home button functionality on Item List Screen and Item Details Screen.

When i press Home Button on Item Details screen it goes back to Home Screen . This is expected behaviour.
But when i press back button on Home screen , it takes me back to the Item Details Screen.(this is what i dont want)

I tried killing the Item Details Screen using finish(), But then the last activity in the activity stack is Item List Screen.
The Back button on Home screen now takes me to the Item List Screen .
Is there any way to clear the activity stack when user is on Home Screen . Any help in this regard will be highly appreciated.


Solution

  • You should launch your Home Screen Activity with additional intent flags:

    // create intent
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    startActivity(intent);
    

    This will clear the activity stack up to the Home Screen activity. This activity will simply be presented, not recreated. Also, this guarantees that there will be only one Home Screen activity which is likely what you want.