Proper use of sub sub fragments with (Child)FragmentManager

前端 未结 1 570
长发绾君心
长发绾君心 2021-02-04 01:00

How do I properly use Fragments in Fragments?

My (simplified) use case is following, I have an activity with a layout fragment and this fragment theirself contains a sub

1条回答
  •  悲哀的现实
    2021-02-04 01:43

    You should add SubFragment to Fragment the same way like you add Fragment to Activity. I mean adding Fragment to Activity should look like:

     @Override
     public void onCreate(Bundle savedInstanceState) {
       ....
       if (savedInstanceState == null){
          //add fragment
          mMainFragment = new MainFragment();
          FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
          transaction.replace(R.id.fragment_main, mMainFragment);
          transaction.commit();
       }
     }
    

    Adding SubFragment to MainFragment should look like:

        public class MainFragment extends Fragment{
    
          @Override
          public View onCreateView(LayoutInflater i, ViewGroup c, Bundle savedInstanceState) {
               ...
            if (savedInstanceState == null){
               mSubFragment = new SubFragment();
    
               //add child fragment
               getChildFragmentManager()
                       .beginTransaction()
                       .add(R.id.fragment_sub, mSubFragment, "tag")
                       .commit();
            }
          }
        }
    

    or you can add child fragment to Fragment in onCreate method

    0 讨论(0)
提交回复
热议问题