如何导航到相同的父母状态

从我从Gmail和TED应用程序观察到的向上导航的行为,它将导航到具有相同状态(滚动位置)的父母,而不像Google在他们的文档“ 实现向上导航”中所说的那样,就像创build父母意图并启动它。

我从Android示例代码实现了代码,并且所有的状态都不见了(所有额外的参数,我以前设置和滚动的位置)。 什么是正确的方法呢? 我无法find任何Android文件。

以下是代码:

public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: Intent upIntent = new Intent(this, MyParentActivity.class); if (NavUtils.shouldUpRecreateTask(this, upIntent)) { // This activity is not part of the application's task, so create a new task // with a synthesized back stack. TaskStackBuilder.from(this) .addNextIntent(new Intent(this, MyGreatGrandParentActivity.class)) .addNextIntent(new Intent(this, MyGrandParentActivity.class)) .addNextIntent(upIntent) .startActivities(); finish(); } else { // This activity is part of the application's task, so simply // navigate up to the hierarchical parent activity. NavUtils.navigateUpTo(this, upIntent); } return true; } return super.onOptionsItemSelected(item); 

}

在我的情况下,我得到了3个活动,说AB和C,当用户从A导航到BI放一些额外的和BI的创build使用额外的从数据库中查询数据填充我的行,当我从C导航回所有额外的东西都消失了,活动B什么都不显示。

android活动的“标准”行为是,每创build一个活动新的意图,都会创build一个活动的新实例(请参阅launchMode-docu here )。 正因为如此,如果您调用navigateUpTo,您的演员似乎已经不存在了。

在你的情况下,我会build议使用

 android:launchMode="singleTop" 

为您的AndroidManifest.xml中的父级活动。 这样你将返回到你现有的活动(只要它在你的任务的后面堆栈的顶部)。 这样你的演员将被保留。

我也不明白,为什么在你提到的Google文档中没有提到这一点,因为这似乎是使用向上导航的行为。

这是可接受的答案的替代解决scheme:

如果您无法更改您的活动的launchMode ,或者如果父活动不在活动栈的顶部(例如,A是C的父活动),则无法使用上述解决scheme。 在这种情况下,您必须扩展您的navigateUpTo调用以告知活动,如果它位于后端堆栈上,则不应重新创build:

 Intent intent = NavUtils.getParentActivityIntent(this); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); NavUtils.navigateUpTo(this, intent); 

我有一个类似的问题,当我在主要活动中使用fragment调用startActivityForResult(),然后尝试使用Up导航从被调用者返回。 通过执行Up导航解决:

 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: setResult(RESULT_CANCELED); finish(); return true; } return super.onOptionsItemSelected(item); } 

在这种情况下,向上button的行为就像一个普通的后退button,所有的状态都被保留下

你可以使用这个:

 @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: super.onBackPressed(); return true; } return super.onOptionsItemSelected(item); } 

您需要将状态保存在父活动中,并在从调用者返回后恢复它。

请参阅使用“保存实例状态”来保存Android活动状态,以获取有关前处理的完整说明以及代码。