A
Fragment
represents a portion of a user interface or an operation that runs within an Activity
. A single activity can contain multiple Fragments and many fragments can be reused in many, different activities. It is not wrong if we say that a fragment is a type of sub-activity that can be utilized again in multiple activities. Although each fragment has each own lifecycle, it is connected with the Activity
it belongs to, so it’s lifecycle is directly influenced by the activity’s lifecycle. The main advantage of using fragments is due to the convenience of reusing the components in different layouts. In this tutorial, we are going to create our own fragments, where each one will be used when the user presses the appropriate button.1. Create the layout of the Main Activity
For this example, we need two different
Buttons
. When a button is pressed, a fragment appears below them. So we will create two different buttons within the main LinearLayout
and a fragment by using the <fragment>
tag.Open
res/layout/activity_main.xml
and go to the “activity_main.xml” tab. Then paste the following code.activity_main.xml:
<? xml version = "1.0" encoding = "utf-8" ?> |
02 | < LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" |
03 | android:layout_width = "match_parent" |
04 | android:layout_height = "match_parent" |
05 | android:orientation = "vertical" > |
06 | < Button |
07 | android:id = "@+id/button1" |
08 | android:layout_width = "fill_parent" |
09 | android:layout_height = "wrap_content" |
10 | android:text = "Fragment No.1" |