Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Actionbar Up button versus system Back button

I'm using the Actionbar and it's "up" button to return from a detail activity to the main activity, which works fine. Similarly, the user can press the system "back" button to return to the main activity.

In my main activity, in onCreate() data is downloaded from the internet to display upon app start. I noticed that when I use the Actionbar "up" button to go from detail to main activity, onCreate() is run, re-downloading the data. But onCreate() is not run when I use the system "back" button, therefore immediately showing the main activity view.

The code I use in the detail activity to implement the "up" button is:

switch (item.getItemId()) {    case android.R.id.home:       Intent intent = new Intent(this, MainActivity.class);       intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);       startActivity(intent);       return true; 

I would like the "up" button to behave like the "back" button and not rerun onCreate(). But I'm unsure how to make this happen, or which code path the "back" button implements to return to the main activity.

Thanks!

like image 224
mraviator Avatar asked Apr 25 '12 16:04

mraviator


People also ask

What is the difference between the up button and back button?

When you press the Back button, the current destination is popped off the top of the back stack, and you then navigate to the previous destination. The Up button appears in the app bar at the top of the screen.

What is the Back button bar called?

The action bar is a primary toolbar inside an activity that can be used to display an activity title and other interactive items. One of the most used items is a Back Navigation Button. The back button is used to move backward from the previously visited screen by the user.

How do you display action bar back button on all versions of Android?

ActionBar actionBar = getActionBar(); actionBar. setHomeButtonEnabled(true);


1 Answers

Instead of starting a whole new activity simply finish the details activity you are in

switch (item.getItemId()) {    case android.R.id.home:       finish();       return true; 

Then you will return to the previous activity on the activity stack (your main activity) and onCreate shouldn't be called

like image 85
dymmeh Avatar answered Sep 24 '22 16:09

dymmeh