mraviator mraviator - 6 months ago 29
Android Question

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!

Answer

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

Comments