从片段调用Fragment,然后返回第一个

时间:2019-04-12 11:10:39

标签: android android-fragments bundle

我通过传递的捆绑包呼叫一个片段。

  Bundle bundle = new Bundle();
                bundle.putStringArrayList(Constants.Bundle.SESSION_ORDER_ID_LIST,session_order_id);
                bundle.putString(Constants.Bundle.SERVICE_ID,service_id);
                bundle.putString(Constants.Bundle.TOTAL_AMT,total_amount);
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.base_frame, CheckoutFragment.newInstance(bundle)).addToBackStack("CheckoutFragment").commit();

然后在TextView上的结帐片段中,点击我致电

getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.base_frame, AddressListFragment.newInstance(bundle)).addToBackStack("AddressListFragment").commit();

然后在AddressListFragment的列表视图setOnItemClickListener上,我想起checkoutFragment我该怎么做?

1 个答案:

答案 0 :(得分:0)

一种更简单的方法是在您的活动中添加以下代码

  /**
 * change fragment by calling from other UI parts
 *
 * @param fragment           fragment to be opened
 * @param isBackPressEnabled allow back or not
 */
public void replaceFragment(Fragment fragment, Boolean isBackPressEnabled) {
    String tag = fragment.getClass().getCanonicalName();
    if (getSupportFragmentManager().findFragmentByTag(tag) != null) return;
    if (isBackPressEnabled) {
        getSupportFragmentManager().beginTransaction().replace(R.id.flContainer, fragment, tag)
                .addToBackStack(tag)
                .commitAllowingStateLoss();
    } else {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.flContainer, fragment, tag)
                .commitAllowingStateLoss();
    }
}

并从片段中这样调用

if (getActivity() != null) {
  ((BaseActivity) getActivity()).replaceFragment(AddressListFragment.newInstance(bundle), true);
}

您不必担心实现问题,只要添加片段容器ID,就可以随时更改其活动状态。