Android-从活动到碎片导航



我正在开发一些应用程序,我有一个问题。

我有:1.活动A(导航抽屉模式)在Framelayout中具有ListFragment:XML:

    <FrameLayout
        ...>
    </FrameLayout>
    <LinearLayout
        ...>
    </LinearLayout>
</android.support.v4.widget.DrawerLayout>
  1. 活动b显示ListFragment中的ListView的详细数据。

我如何从活动B进行返回(使用导航UP按钮),并保存列表范围的UI(如果我使用Home Back返回)的列表fragment的UI(活动重新创建)。顺便说一句,如果我按下手机上的后退按钮,活动不会重新创建并以先前的状态返回。

当您使用导航时,重新创建了先前的活动。为了防止在保留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);
}

i在清单中还指定了launchMode="singleTop"。但是我不确定是否有必要。

您可以做的一件事以防止重新创建的第一个活动是在按下该返回按钮时在第二个活动上调用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);
    }
}

最新更新