简体   繁体   中英

How to get back to parent fragment?

In parent fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_parent, container, false);

        //child fragment
        FragmentManager childFragMan = getChildFragmentManager();
        FragmentTransaction childFragTrans = childFragMan.beginTransaction();
        ChildFragment childFragment = new ChildFragment ();
        childFragTrans.add(R.id.FRAGMENT_CHILD, childFragment);
        childFragTrans.commit();

Then in child fragment i need to get back to Parent fragment (hide child fragment) How to implement that?

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_parent, container, false);

    if (savedInstanceState == null) {
        //child fragment
        FragmentManager childFragMan = getChildFragmentManager();
        FragmentTransaction childFragTrans = childFragMan.beginTransaction();
        ChildFragment childFragment = new ChildFragment ();
        childFragTrans.add(R.id.FRAGMENT_CHILD, childFragment, "childFragment");
        childFragTrans.commit();
    }

Then

FragmentManager childFragMan = getChildFragmentManager();
Fragment childFragment = childFragMan.findFragmentByTag("childFragment");
FragmentTransaction childFragTrans = childFragMan.beginTransaction();
childFragTrans.remove(childFragment);
childFragTrans.commit();

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