All you need to know about Fragment. What is Fragment in Android?

In this blog, we are going to discuss what is a fragment. How to use it, the lifecycle of fragments. Also, we will see an example of how fragments are used.

A Fragment is a part of an Activity, there can be more than one fragment in an activity. The Fragment is also known as sub-activity because the fragment allows more modular designs in an activity. Fragments represent multiple screens inside one activity.

Fig: An example of how two UI modules defined by fragments can be combined into one activity for a tablet design, but separated for handset design.

As we already know that each activity has its own lifecycle, so the fragment lifecycle is affected by the activity lifecycle as the fragments are included in the activity. Want to know about the Activity LifeCycle than click here.

Before going to discuss how to use fragments, let’s see the lifecycle of the fragment.

Life Cycle of Fragment

Android fragments have their own lifecycle methods, which is very similar to an android activity lifecycle.

Fig: Fragment LifeCycle

Here is the list of methods which are overridden in fragment –

  • onAttach(activity): The fragment instance is associated with an activity instance. The fragment and the activity are not fully initialized. It is called only once when it is attached to an activity.
  • onCreate(Bundle): The system calls this method when initializing the fragment.
  • onCreateView(LayoutInflater, ViewGroup, Bundle): The system calls this callback when it’s time for creates and returns view hierarchy. To draw a UI for the fragment, first must return a View component from this method that is the root of the fragment’s layout.
  • onActivityCreated(Bundle):The onActivityCreated() is called after the onCreateView() method when the host activity is created. In this method, the objects are instantiated which require a Context object
  • onStart(): onStart() method is called once the fragment gets visible.
  • onResume(): the fragment becomes interactive.
  • onPause(): The system calls this method as the first sign that the user is leaving the fragment. This method is called when the fragment is no longer interactive.
  • onStop(): Fragment going to be stopped by calling onStop(). The fragment is no longer visible.
  • onDestroyView(): Fragment view will destroy after calling this method, it cleans up all resources form the view.
  • onDestroy(): onDestroy() called to do a final clean-up of the fragment’s state.
  • onDetach(): It is called quickly before the fragment no longer being linked with its activity.

Important points about Fragment:

  • A fragment has its own layout and behavior with its own life cycle methods.
  • One can add or remove fragments in an activity while the activity is running.
  • One can combine multiple fragments in a single activity to build a multi-pane UI.
  • A fragment can be used in multiple activities.
  • The fragment life cycle is closely related to the life cycle of its host activity which means when the activity is paused, all the fragments available in the activity will also be stopped.
  • Fragments were added to the Android API in the Honeycomb version of Android which API version 11.

Let’s discuss it a little bit more with an example

This involves some simple steps to create fragments.

  • First of all, decide how many fragments you want to use in an activity. For example, let’s we want to use two fragments.
  • Next based on the number of fragments, create classes that will extend the Fragment class, which include the above-mentioned lifecycle methods.
  • Corresponding to each fragment, you will need to create layout files in the XML file.
  • Finally, change the activity file to define the actual thought of replacing fragments based on the requirement.

fragment_fragment1.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#FF4B4B"
tools:context=".Fragment1Fragment">

<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />

</FrameLayout>

fragment_fragment2.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
android:background="#5872FF"
tools:context=".Fragment2Fragment">

<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_blank_fragment" />

</FrameLayout>

Fragment1Fragment.java

package com.codewithgolap.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1Fragment extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment1, container, false);
}
}

Fragment2Fragment.java

package com.codewithgolap.fragment;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2Fragment extends Fragment {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_fragment2, container, false);
}

activity_main.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity">

<fragment
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/fragment1"
android:name="com.codewithgolap.fragment.Fragment1Fragment"/>
<fragment
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/fragment2"
android:name="com.codewithgolap.fragment.Fragment2Fragment"/>

</LinearLayout>

MainActivity.java

package com.codewithgolap.fragment;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

Output:

Types of Fragments

  • Single frame fragments: Single frame fragments are using for handheld devices like mobiles, here we can show only one fragment as a view.
  • List fragments: fragments having a special list view is called a list fragment
  • Fragments transaction: Using the fragment transaction. we can move one fragment to another fragment.

Find it helpful, then follow my website GBAndroidBlogs for more content like this

Hi everyone, myself Golap an Android app developer with UI/UX designer.