Fragments are use to develop dynamic and flexible or consistent User Interface(UI) design that can be supported by all screen sizes from small to large. In short, we can build Multi-pane UI using Fragments. We can divide the Activities into different reusable components which are known as Fragments. Fragments can be reused within multiple activities. Each Fragment has its own lifecycle and Layout and they are independent to each other that are embedded into an Activity. There are two class, Fragment and FragmentActivity that must be extended by the subclass of it. To know more about Fragment VS FragmentActivity. We can define a static or dynamic layout using Fragment.
To Define a Static Layout
In this case, you need to use the fragment placeholder instead of FrameLayout in your MainActivity layout file, like this:
<RelativeLayout>
<fragment
android:id="@+id/Fragment_A"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="26dp"
class="com.pkg.Fragment_A" ></fragment>
<fragment
android:id="@+id/Fragment_B"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="113dp"
class="com.pkg.Fragment_A" ></fragment>
</RelativeLayout>
You can use this approach, when you have different static layout files for different device configuration.
To Define a Dynamic Layout
In this case, you can add, remove or replace Fragments at run-time using FragmentManager. You can use the FrameLayout placeholder instead of fragment in your layout file or use container views to place the Fragments.
<RelativeLayout>
<FrameLayout
android:id="@+id/container_A"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="26dp"
class="com.pkg.Fragment_A" ></FrameLayout>
<FrameLayout
android:id="@+id/container_B"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="113dp" ></FrameLayout>
</RelativeLayout>
Comments
Post a Comment