我遇到一个问题,我有一个设置活动,可以从MainActivity或NewsArticles活动(MainActivity是NewsArticles的父级)中启动,我想导航回逻辑父级。查看文档,似乎您必须在清单中声明父活动:
<activity
android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".NewsArticles"
android:label="@string/news_articles_title"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
<meta-data android:name="android.app.default_searchable"
android:value=".SearchActivity"/>
</activity>
<activity
android:name=".SettingsActivity"
android:label="@string/settings_title"
android:parentActivityName=".NewsArticles">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".NewsArticles" />
</activity>
因此,我已宣布我的“设置活动”将“ NewsArticles”活动作为其父项。但是,也可以从MainActivity中启动“设置活动”-如何处理这种情况?在我的SettingsActivity中:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
ActionBar actionBar = this.getSupportActionBar();
if(actionBar!= null)
actionBar.setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
//FIXME when user press back it always goes back to main activity regardless
//The settings activity can be launched from either the main activity or the news articles activity
//So we want to navigate up from the same task.
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
我知道,当用户浏览活动时,它应该创建一个活动任务,并且如果用户按下返回键或向上按钮,则应该从启动它的逻辑父级向上导航。我的应用程序处于启动模式单顶模式,在这种情况下,即使NewsArticles活动被声明为父级,我也总是回到MainActivity-有人可以建议吗?