Android - 从 Activity 向上导航到 Fragment [英] Android - Navigation Up from Activity to Fragment
问题描述
我正在开发一些应用程序,但遇到一个问题.
I'm developing some application and I have one problem.
我有:1. Activity A(Navigation Drawer 模式)和 FrameLayout 中的 ListFragment:xml:
I have : 1. Activity A (Navigation Drawer pattern) with ListFragment in FrameLayout: xml:
<FrameLayout
...>
</FrameLayout>
<LinearLayout
...>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
- Activity B 显示 ListFragment 中 ListView 的详细数据.
如何通过保存 ListFragment 的 UI(使用 Home Back 返回时重新创建活动)从活动 B 返回(使用向上导航按钮)到活动 A.顺便说一句,如果我按下手机上的后退按钮,活动不会重新创建并返回到以前的状态.
How can I go back (using Navigation Up Button) from activity B to Activity A with saving UI of the ListFragment (Activity re-creates if I go back using Home Back). Btw, if I press the back button on my phone, activity does not re-create and returns in previous state.
推荐答案
当您使用向上导航时,将重新创建之前的活动.为了防止在保留 UP 导航时发生这种情况,您可以获取父 Activity 的意图,如果存在则将其置于最前面,否则创建它.
When you use UP navigation, then the previous activity is recreated. To prevent that from happening while you preserve the UP navigation, you can get the intent of the parent activity, and bring it to front if it exists, otherwise create it if not.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Intent parentIntent = NavUtils.getParentActivityIntent(this);
parentIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(parentIntent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
我还在 Manifest 中指定了 launchMode="singleTop"
.但我不确定这是否有必要.
I also specified launchMode="singleTop"
in the Manifest. but I am not sure if that was necessary.
这篇关于Android - 从 Activity 向上导航到 Fragment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!