片段管理和导航(交付应用程序)

时间:2015-07-29 16:50:51

标签: android navigation fragment state

我正在尝试构建一个交付应用。我有一个可供选择的产品清单。在用户选择产品之后,他将通过一系列阶段来定义特定产品的附加内容和选项。

产品清单:

The list of products

然后,让我们说有人点击其中一个产品,我们去控制器FragmentActivity:

enter image description here

页面底部的小计和页面底部的按钮属于片段活动。然后我在中心布局放置一组单选按钮。到目前为止一切都很好。点击按钮引线替换片段:

enter image description here

到目前为止,一切都很美好。我可以通过片段访问按钮和小计。但是,如果我按下设备上的后退按钮,它会将我带回产品列表而不是之前的片段。即使我设法回到之前的片段,它也会失去radiobutton选择。

然后下一个片段是产品及其附加物的计算:

enter image description here

当我按下按钮时,我只是在片段中使用finish(),它会将我带回产品列表,这是我想要的结果。但是,我需要知道我是从产品列表中找到的,因此我可以将该产品添加到为交货订单构建的购物车中。

我真的很擅长使用片段,但我可以传递参数。我正在努力的是通过控制片段的FragmentActivity来控制片段的导航。此外,我正在努力保持片段的状态(记住用户输入)。最后,我需要回到正在构建的项目结果的产品列表,以便将其添加到购物车。

我会朝着正确的方向前进吗?我如何实现这些功能(导航,片段状态,返回以前的活动与一些数据,因为我只使用完成()),非常感谢你们!

1 个答案:

答案 0 :(得分:2)

您可以在片段之间导航,只需将它们添加到后台堆栈中,如下所示:

// Works with either the framework FragmentManager or the
// support package FragmentManager (getSupportFragmentManager).
getSupportFragmentManager().beginTransaction()
                           .add(detailFragment, "detail")
                           // Add this transaction to the back stack
                           .addToBackStack()
                           .commit();

这样,当您单击后退按钮时,它将不会从堆栈中加载先前的活动,而是在后台堆栈中添加的先前片段。您可以在此处找到更多详细信息:http://developer.android.com/training/implementing-navigation/temporal.html

在要保存和检索数据的每个片段上使用onSaveInstanceState(Bundle savedInstanceState)和onActivityCreated(Bundle savedInstanceState)。然后执行以下操作:

public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        //Restore the fragment's state here
        String yourString  = savedInstanceState.getString("key");
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    //save whatever you want into the bundle
    savedInstanceState.putString("key", "your_value");
    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

您可以将任何想要的内容保存到Bundle中。从字符串到Parcelables和Serializables。更多信息:http://developer.android.com/reference/android/os/Bundle.html