Go back to Activity without recreating (without invoking onCreate())

筅森魡賤 提交于 2019-12-12 10:49:53

问题


I would like to ask similar question to:

Go back to previous screen without creating new instance

However I don't want Activity A go through onCreate callback, I would like to return to previous instance in the same state. How to achieve that without calling multiple finish() ?


回答1:


There's no need to finish() activities as you navigate through your application. Instead, you can maintain your Activity back-stack and still achieve your goal. Let's say you have 4 activites like so:

A --> B --> C -->D

where D is the topmost activity and A is root activity. If you are 'falling back' to activity B, then you'll need to do two things in order to avoid hitting B's onCreate method.

1.) Make B a "SingleTask" activity. You can do this in the Android Manifest. To be brief, this means that only one 'instance' of B will ever exist within this Task. If B is already running when it's called then it will simply be brought to the front. This is how you do that.

  <activity
        android:name=".ui.MyActivity"
        android:launchMode="singleTask"/>

But you don't want to just bring B to the front. You want to 'fall back' to B so that your stack looks like

A--> B

2.) Add this flag to your intent that 'starts' B. This ensures that C and D are removed.

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Now when 'D' calls new Intent to B, B will be resumed and C and D will be removed. B will not be recreated, it will only call onNewIntent.




回答2:


When navigating from A to B do not finish Activity A. When navigating from B to C finish Activity B. When navigating from C to D finish Activity C.

So from wherever you navigate back finish current Activity and Activity A will get resume again not get created.



来源:https://stackoverflow.com/questions/36599717/go-back-to-activity-without-recreating-without-invoking-oncreate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!