简体   繁体   中英

How to get Back button(on device) like functionality on app bar back arrow on top right corner

I have a button which takes me back to the home screen. But this loads the screen everytime i click on that button. But when I press the back button(given by android on phone) then it doesn't load the page again and again. I don't want that my activity is loaded again and I want to get the same functionality as the back button. I have tried

Intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)

But this loads the whole activity again and again. Any suggestions are valuable. The main screen has a map which gets loaded evertime I hit that button.

You need to understand two concepts here -

  1. Task and Back Stack
  2. LaunchMode

Task and Back Stack :

A task is a collection of activities that users interact with when performing a certain job. The activities are arranged in a stack—the back stack)—in the order in which each activity is opened. In simple word back stack is just an stack of activity which grown as user start launching new activities in FILO (First in Last Out) manner.

If the user presses the Back(on device) button, that new activity is finished and popped off the stack, which will cause last activity on stack to call onResume() .

on Another hand

If you are calling finish() on an activity and manually starting a new activity with new Intent() then on stack, new activity will be on top and will start its own activity life-cycle .

LaunchMode

Launch mode are nothing but flags to show android that how the corresponding activity should start.

android:launchMode=["standard" | "singleTop" |"singleTask" | "singleInstance"]

standard: Default. The system always creates a new instance of the activity in the target task and routes the intent to it.

singleTop: If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.

A good read on Task and Back Stack and Activity Tag


Now coming back to your question, if you will add flag android:launchMode="singleTop" to your home screen activity tag under AndroidManifest.xml as follows -

<activity 
    ... 
    android:launchMode="singleTop">
</activity>

then activity will not be recreated and you will not get screen loading again. There are more efficient way to navigation in android and clearly this is not the best way. Using fragments and navigation architecture are available to make life easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM