简体   繁体   English

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

[英]How to navigate through fragments without adding it to the backstack

I have 3 Fragments A , B and C . 我有3个Fragments ABC。 When I press a button in fragment A , I have to navigate to fragment B (to initialize it) which should implicitly navigate to fragment C . 当我按下片段A中的按钮时,我必须导航至片段B (以对其进行初始化),该片段应隐式导航至片段C。 Meanwhile, it should not be added to backstack, so that when I return back from fragment C , it should directly come back to fragment A . 同时,不应将其添加到堆栈,以便当我从片段C返回时,应直接返回片段A。 Can someone tell how to do this? 有人可以告诉我该怎么做吗?

I have tried not adding it to the backstack, but it doesn't work out. 我试过不将其添加到堆栈中,但无法解决。 It throws NullPointerException while coming back. 返回时将抛出NullPointerException

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

if you pass argument correctly to your fragment, when pop from backStack this bundle restore well! 如果您正确地将参数传递给您的片段,则当从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");
    }
}

and just use replace for adding to backStack: 并使用replace来添加到backStack中:

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

and implement onBackPressed() : 并实现onBackPressed()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM