dynamic Fragments in Android
this post talks about how to dynamically show Fragments at runtime.
dependencies for this post:
last time, the Fragment was statically called in an XML layout file. this time, it will be created at runtime in the Activity in which the Fragment is located.
- create the subclass of Fragment, e.g. to be "Frag1", and the XML layout file that it should use, e.g. to be "frag1.xml".
- modify the XML layout (e.g. "main.xml") for the main Activity, so that there is an empty ViewGroup in which the Fragment should be located. give this ViewGroup an id. as an example, just define an empty <FrameLayout /> as the root element of this XML layout:
<!-- in main.xml --> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_fragment_container" android:layout_width="match_parent" android:layout_height="match_parent" />
- load the XML layout in the main Activity class's method as usual. after that, use a few lines of code to have the Fragment displayed:
//some method e.g. onCreate in the MainActivity class Fragment f1=new Frag1(); f1.setArguments(mBundle); FragmentManager fmgr=getFragmentManager(); FragmentTransaction trans=fmgr.beginTransaction(); trans.add(R.id.my_fragment_container, f1); trans.commit();
here,"mBundle" is a Bundle of key-values pairs as the parameters for the Fragment to use, and it can be null.
- done.
reference: