如何浏览片段而不将其添加到堆栈中

时间:2019-01-22 14:04:15

标签: java android android-fragments

我有3个Fragments A B C 。当我按下片段 A 中的按钮时,我必须导航至片段 B (以对其进行初始化),该片段应隐式导航至片段 C 。同时,不应将其添加到堆栈中,以便当我从片段 C 返回时,它应直接返回片段 A 。有人可以告诉我该怎么做吗?

我尝试过不将其添加到堆栈中,但是无法解决。返回时会抛出NullPointerException

final int fragId = manager
                    .beginTransaction()
                    .replace(R.id.main_container, fragment, MAIN_FRAGMENT_TAG )
                    .commitAllowingStateLoss();

1 个答案:

答案 0 :(得分:0)

如果您正确地将参数传递给您的片段,则从backStack弹出时,此捆绑包将恢复正常!

 public class HomeProfileFragment extends Fragment {

    public static HomeProfileFragment newInstance(String name){
        Bundle args = new Bundle();
        args.putString("ARG_NAME",name);
        HomeProfileFragment fragment = new HomeProfileFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String name = getArguments().getString("ARG_NAME");
    }
}

,只需使用replace即可添加到backStack:

getSupportFragmentManager()
                .beginTransaction()
                .replace(R.id.frag_container, fragment, fragment.getClass().getSimpleName())
                .addToBackStack(fragment.getClass().getSimpleName()).commit();

并实施onBackPressed()

@Override
public void onBackPressed() {
    if (fragmentManager.getBackStackEntryCount() > 0)
        fragmentManager.popBackStack();
    else
        super.onBackPressed();
}