简体   繁体   中英

How to navigate through fragments without adding it to the backstack

I have 3 Fragments A , B and C . 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 . 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 . 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.

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!

 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:

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

and implement onBackPressed() :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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