Dynamically add fragment into fragment

前端 未结 4 1747
花落未央
花落未央 2020-12-05 03:07

I haven\'t been able to find a way how to dynamically add fragment into existing dynamically added fragment. Do you know, if it is possible?

I am generating fragment

4条回答
  •  感情败类
    2020-12-05 04:07

    I assume the problem that you are running into is that there is not an inflated view to add the fragment to because the original fragment, FRAG4_TAG, has not been inflated before you are trying to add it.

    You can pass enough information to FRAG4_TAG in the Arguments to let it know that it should create and add a fragment (or what all fragments you need it to have) to itself during it's onCreateView, after the view has been inflated...

    The layout for the activity...

    
    
            
    
        
    
    

    The Activity...

    public class MyActivity extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.main);
    
            FragmentManager fm = getFragmentManager();
            FragmentTransaction ft = fm.beginTransaction();
    
            Fragment fragOne = new MyFragment();
            Bundle arguments = new Bundle();
            arguments.putBoolean("shouldYouCreateAChildFragment", true);
            fragOne.setArguments(arguments);
            ft.add(R.id.main_frag_container, fragOne);
            ft.commit();
    
        }
    }
    

    The layout for the fragment...

    
    
        
    
        
    
    

    The fragment...

    public class MyFragment extends Fragment {
        @Override
        public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
            ViewGroup layout = (ViewGroup) inflater.inflate(R.layout.frag_layout, container, false);
    
            boolean shouldCreateChild = getArguments().getBoolean("shouldYouCreateAChildFragment");
    
            if (shouldCreateChild) {
                FragmentManager fm = getFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
    
                fm.beginTransaction();
                Fragment fragTwo = new MyFragment();
                Bundle arguments = new Bundle();
                arguments.putBoolean("shouldYouCreateAChildFragment", false);
                fragTwo.setArguments(arguments);
                ft.add(R.id.frag_container, fragTwo);
                ft.commit();
    
            }
    
            return layout;
        }
    }
    

    This example covers the case where you need to dynamically add fragments to a fragment that HAS NOT already been inflated and added to the hierarchy. Adding a fragment to a fragment that HAS already been inflated and added to the hierarchy is as simple as just specifying the target fragments container that you want to add to by ID like you would normally.

提交回复
热议问题