Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The proper way to handle "Up" Navigation according to guidelines

I do totally agree with the Navigation below

enter image description here

Imagine that the Book detail is made in different instances of a BookDetailActivity.

The stack before pressing up in book2 detail is:

  • BookDetailActivity (Book 2 - You are here)
  • BookDetailActivity (Book 1)
  • AllBooksActivity

If I follow the guidelines I will use:

     Intent parentActivityIntent = new Intent(this, AllBooksActivity.class);
        parentActivityIntent.addFlags(
                Intent.FLAG_ACTIVITY_CLEAR_TOP |
                Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(parentActivityIntent);
        finish();

But the big problem with this code is that BookDetailActivity (Book 1) is still alive!

Pressing back button after "up" would bring the detail of Book 1.

How can I kill all the BookDetailActivity that are between the original AllBooksActivity and the activity where I pressed up?

like image 518
Waza_Be Avatar asked Dec 26 '12 12:12

Waza_Be


1 Answers

The related guidelines article notes the following:

Implementation Note: As a best practice, when implementing either Home or Up, make sure to clear the back stack of any descendent screens. For Home, the only remaining screen on the back stack should be the home screen. For Up navigation, the current screen should be removed from the back stack, unless Back navigates across screen hierarchies. You can use the FLAG_ACTIVITY_CLEAR_TOP and FLAG_ACTIVITY_NEW_TASK intent flags together to achieve this.

Since you're doing that, BookDetailActivity1 should be closed by FLAG_ACTIVITY_CLEAR_TOP. The only way if it could be alive and shown on pressing Back is if it would have been started before AllBooksActivity.

As for not needing FLAG_ACTIVITY_NEW_TASK (suggested by android developer's answer):

When using this flag, if a task is already running for the activity you are now starting, then a new activity will not be started; instead, the current task will simply be brought to the front of the screen with the state it was last in.

...so if your activity exists, it will not start a new task.

like image 151
molnarm Avatar answered Oct 20 '22 07:10

molnarm