Android - 从活动到片段的导航

时间:2015-05-05 17:25:17

标签: android android-fragments android-activity android-navigation android-savedstate

我正在开发一些应用程序,但我遇到了一个问题。

我有: 1. FrameLayout中带有ListFragment的活动A(导航抽屉图案): XML:     

    <FrameLayout
        ...>

    </FrameLayout>

    <LinearLayout
        ...>

    </LinearLayout>

</android.support.v4.widget.DrawerLayout>
  1. 活动B,显示ListFragment中ListView的详细数据。
  2. 如何通过保存ListFragment的UI,从活动B返回(使用导航按钮)到活动A(如果我使用Home Back返回,则重新创建活动)。 顺便说一句,如果我按下手机上的后退按钮,活动就不会重新创建并返回之前的状态。

2 个答案:

答案 0 :(得分:11)

使用“向上”导航时,将重新创建上一个活动。为了防止在保留UP导航时发生这种情况,您可以获取父活动的意图,如果存在则将其置于前面,否则创建它。否则就创建它。

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"。但我不确定是否有必要。

答案 1 :(得分:0)

您可以做的一件事是阻止第一个活动重新创建,只需在按下该按钮时调用第二个活动上的finish()

未经过测试,但我认为该ID为android.R.id.home,因此您只需在第二项活动中覆盖onOptionsItemSelected,如下所示:

/**
 * Handles the selection of a MenuItem.
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch(item.getItemId()){
        case android.R.id.home:
            finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}
相关问题