Learn Android Development For Beginners

Fragment

Fragment is the reusable component that was introduced with Android 3.0. It encapsulates functionality so that it is easier to reuse within the activities and layouts. Fragment has its own life cycle but it depends on its Activity. It cannot be used apart from the activity. If the activity is stopped then the fragment cannot be started and if the Activity is destroyed all fragments inside that activity destroyed automatically.

Fragment has its own layout or user interface and it is also possible to create Fragment without user interface. Fragment can be added dynamically or statically in the activity.

Create Fragment

Fragment creation is almost similar to the Activity. Drive class from the Fragment class and do your work as we do in Activity. You can also use Android studio to create new Fragment. Create new Android project or Open the existing android application. In this example we will manage fragment separate from the activities. Create new package by right clicking on the java folder as you can see in image below

click on New -> Package and in the poped up window type “com.example.fragment”.

Press the “OK” button and android studio will create new package folder under the “java/com.example” folder. Now you can manage your fragments in this package.

Now right click on the “fragment” package to add fragment using designer. Click on New -> Android Component and it opens the window where you enter the name of the component and its type.

Enter InformationFragment as "Name", select Fragment as "Kind" and checked the “Create layout file” check box. Now press OK Button. The Android studio automatically creates the fragment class for and opens a new window where you need to enter information for your layout.

In this window enter “fragment_information” as “File Name”, “LinearLayout” as “Root Element”. The root element is an auto suggested list control. And you can also select Linear Layout form that list. The Linear layout is a type of layout and we will learn about it in next chapters. Press the “OK” button to create a layout for your Fragment.

Open the InformationFragment.java file and see the code. If Android Studio does not installed all API properly or there is some other issue. It might give you error of wrong version of the fragment as you can see in image below.

Remove the “import android.app.fragment;” statement and click on the “Fragment” red text and press “ALT + Enter” key. It opens a suggestion to pick available fragment packages. Select the other one from the list.

e.g. “android.support.v4.app.Fragment” is valid package in my project. Now have a look on the code of the fragment class.

 public class InformationFragment extends Fragment {
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_information, container, false);
    }

 }

    

A Fragment is lot of similar to the Activity and it has its own life cycle. We will learn its life cycle in detail later. Fragment contains callback methods similar to activity such as onStart, onPause and onStop.

To provide a layout to the Fragment, override/implement the onCreateView callback method. Andriod system calls this method when it’s time to draw the layout for the Fragment. onCreateView provides some parameters that have different purposes. The LayoutInflater instance is used for to inflate the layout from the layout xml resources. The Container is the parent ViewGroup (from the activity's layout) in which your fragment layout will be inserted. The savedInstanceState parameter is a Bundle that provides data about the previous instance of the fragment, if the fragment is being resumed.

For setting the layout of the Fragment set the layout using the “inflater.inflate();” method and pass the layout id as “R.layout.fragment_information”, set the ViewGroup as “container” and set attachToRoot as false because in our case the fragment is already attached to the container.

Set Fragment Layout

The layout designing for the fragment is same as Activity. The layout contains the controls definition in the XML and you can also design using the Designer. Open the “fragment_information.xml” layout file from the “layout” folder and add the two TextView in it. One is for title and second is for the description.

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text= "What is Lorem Ipsum"
        android:layout_margin="6dp"
        android:textAppearance="@android:style/TextAppearance.Large"
        android:textColor="#1800ff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry..."
        android:id="@+id/textView2"
        android:layout_margin="6dp"
        android:layout_gravity="center_horizontal" />
 </LinearLayout>
    

The design of the above XML will look like the image below.

Add Fragment in the Activity

The Fragment always render inside the Activity like controls in other programming languages. There are two ways to add fragment inside the Activity.

1. Add inside the Layout File

You can add <fragment> inside the layout file of the activity and specifies the properties. See the activity layout file having one fragment in it.

    
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container123"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame">

      <fragment
        	android:name="com.example.fragment. InformationFragment "
        	android:layout_height="match_parent"
        	android:layout_width="match_parent">
        </fragment>

    </FrameLayout>
    

The <fragment> tag inside the activity layout specifies the fragment. The android.name property specifies the Fragment class to instantiate in the activity. In above example android:name = "com.example.fragment.AboutFragment" specifies the InformationFragment to be instantiate. When the system creates this activity layout, it instantiates each fragment specified in the layout and calls the onCreateView() method to get the layout for each fragment's. The system inserts the View returned by the fragment directly in place of the <fragment> element.

2. Add Programmatically

Fragment can be added anytime in the activity layout while activity is running. For this you need to specify any container(ViewGroup) in the activity layout in which to place the fragment e.g. add the <LinearLayout> inside the activity layout and set its id. In this example set the id for the fragment container is android:id="@+id/container”.

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    </LinearLayout>

 </FrameLayout>
 

Now go into the activity class where you want to add the fragment. Get the supported fragment manager using “getSupportFragmentManager()” statement and get the transaction from activity using “beginTransaction()” method of the fragment manager.

 FragmentManager manager = getSupportFragmentManager();
 
 manager.beginTransaction()
                    .add(R.id.container, new InformationFragment())
                    .commit();

    

Add the fragment into the activity using “add()” method, the first argument of the add method is the container id (“R.id.container”) in which the fragment to insert and the second argument is the instance (“new InformationFragment()”) of the fragment to add.

Once you've made your changes with FragmentTransaction, you must call commit() for the changes to take effect.

;