应用中大部分时候用的都是一般的Back Navigation,对Up Navigation不熟导致练习的时候出了点小问题。
配合ActionBar中的setDisplayHomeAsUpEnabled(true)
方法,我希望点击ActionBar上的Up按钮时返回到指定的目标Activity(调用NavUtils.navigateUpFromSameTask
或NavUtils.navigateUpTo
),但结果有点不如意,系统总是会把目标Activity先销毁(OnDestroy
),然后在启动(OnCreate
),而我希望是不销毁而直接调用目标Activity的OnNewIntent
方法。
网上找了一圈发现答案在官方文档里……,要实现期望的Up Navigation是需要些步骤的:
- 首先指定ParentActivity,表明Up的具体目标。
- ParentActivity对应的launchMode设置为SigleTop
官方文档提示这两个步骤需要注意的地方:
如果是4.0以上可以直接在Manifest里相应的<activity>标签里设置
android:parentActivityName
属性。
如果是兼容4.0以下,需要在<activity>内使用<meta-data>来指定ParentActivity
<activity
android:name="com.example.myfirstapp.DisplayMessageActivity"
android:label="@string/title_activity_display_message"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
</activity>
另外如果ParentActivity的
launchMode
如果没有设置成singleTop
而是standard
,使用一个flag设置为FLAG_ACTIVITY_CLEAR_TOP
的Intent,能达到一样的效果。
Intent upIntent = new Intent(this,DestinationActivity.class);
upIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
NavUtils.navigateUpTo(this,upIntent);
另外官方文档说:If the parent activity has launch mode <standard>, and the up intent does not contain FLAG_ACTIVITY_CLEAR_TOP, the parent activity is popped off the stack, and a new instance of that activity is created on top of the stack to receive the intent.
也就是我之前出现的问题,ParentActivity的launchMode=standard
并且upIntent也没有设置flag是FLAG_ACTIVITY_CLEAR_TOP
,系统会把parentActivity先弹出栈,然后在栈顶重建一个ParentActvity的实例。
这样结果就如愿了。