Introduction to Fragments in Android

Tushar Tambi
AndroidDevelopers
Published in
6 min readSep 24, 2020

First Of All, If you do not have any prior knowledge of Android Development then you can refer it here.

Also, If you want to learn about the basic of android app components then you should refer here:

So, I assume by now that you have a basic knowledge of android app development and Android App Components. So, let’s start with the Activities and their lifecycles.

As we all know Android Apps can be written using Kotlin, Java and C++ languages. So, you can write them in any language that you want. This tutorial is based on Java.

Fragment

Fragment can be viewed as a subactivity which has its own Lifecycle and which can be add or remove while an activity is running (which is a better way).

Structure

There is a host activity that host the fragments and the lifecycle of the fragment is directly affected by this host activity i.e. when the host activity is destroyed all fragment inside that activity get destroyed, in a similar fashion when host activity is paused all fragment gets paused and on a resume, all fragments get resumed.
Although when the host activity is running then you can manipulate each fragment independently as per requirement.

Why Fragment ?

Now you all are must be thinking that why fragment when we have activities? So your reaction on the fragment is like

So, here is the reason that why we use them:

Before fragment introduction, we only able to show a single activity on the screen and not able to divide the screen into different parts but after the fragments, boom! we can add as many subactivities as we want for our screen which makes our android application more useful. In other words, we get more flexibility using fragments.

Fragments are used primarily to support more dynamic and flexible UI designs on large screens, such as tablets. Because a tablet’s screen is much larger than that of a handset, there’s more room to combine and interchange UI components. Fragments allow such designs without the need for you to manage complex changes to the view hierarchy.

For example, suppose you are building a music app.
Now consider the scenario where you are using a tablet. here what you can do is you can divide a screen into two parts, on the left side of the screen you can show a list of all the songs and on the right you can show the currently playing song. This can be down by using fragment without worrying about the complex design of the application.
But if you talk about a simple mobile device then you can start a new activity and then in that new activity, you can use the fragment to the upcoming songs.
This is how fragments are very important in terms of uses and also to increase the flexibility of our product.

Android Fragment Lifecycle Method

Reference: https://www.javatpoint.com/android-fragments

Let’s take a look at these lifecycle methods:

Reference: https://www.javatpoint.com/android-fragments

Creating a Fragment

Now let’s first talk about how many ways we can create and add fragments to our activity. So basically there are two ways to do so.

  1. by adding a fragment to layout file
  2. by adding a fragment at the run time

Note: Adding a fragment at runtime is a good practice.

In the below example we will add fragment in the layout file.

Create a new project in Android Studio.

MainActivity.java

package com.example.fragmentdemo;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);
}
}

So here is the first activity after starting our android project, MainActivity.java

activity_main.xml

<?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:orientation="horizontal"
android:layout_height="fill_parent"
tools:context=".MainActivity">
<fragment
android:id="@+id/fragment1"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.fragmentdemo.Fragment1"/>
<fragment
android:id="@+id/fragment2"
android:layout_width="0px"
android:layout_height="match_parent"
android:layout_weight="1"
android:name="com.example.fragmentdemo.Fragment2"/>
</LinearLayout>

Here in the activity_main.xml, we are adding two fragments by using <fragment/> tags. There is an attribute i.e. name=” ”. In this we are passing the name of the class where we have our code for further operation on fragment.

fragment_1.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"
tools:context=".Fragment1"
android:background="#F0FFFF">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_fragment_1" />
</FrameLayout>

fragment_2.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"
tools:context=".Fragment2"
android:background="#F5F5DC">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_fragment_2" />
</FrameLayout>

Above two codes fragment_1.xml and fragment_2.xml are the layout files for our fragment.

These are same as we use in normal layout file of our activity. So, here you will create a layout for your fragment.

Fragment1.java

package com.example.fragmentdemo;import android.os.Bundle;import androidx.fragment.app.Fragment;import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment1 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_1, container, false);
}
}

Fragment2.java

package com.example.fragmentdemo;import android.os.Bundle;import androidx.fragment.app.Fragment;import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment2 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_2, container, false);
}
}

Above two codes i.e. Fragment1.java and Fragment2.java handle the events that we want to perform using our fragments.

Remember in our activity.java file we have a function onCreate() here also we have onCreate() method but an addition to which we also have onCreateView() that is executed once after you first create your fragment.

Here we are inflating the view of our fragment and returning it to our parent layout. you remember we use “name” tag inside our layout file this is the reason we were using them.

Note: Remember whatever you did in your onCreate() method in an activity you will perform all these activities in the onCreateView() now.

// if you want to initialise any components in onCreateView() then //this is how you should do it.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
// suppose you want to initialise a button thenview V= inflater.inflate(R.layout.fragment_2, container, false);Button btn= V.findViewById(R.layout.id);// if you want to use this in onCreate() then you must declare //button as a global memberreturn V;
}

After running your application you will get a screen like this.

Congratulations! you have just learned the basics of Fragment, one more steps towards learning of Android App Development.

Now try to create more application by yourself and learn more facts about fragments.

Important Links:

Download Java: https://www.java.com/en/download/

Java Tutorials: https://www.tutorialspoint.com/java/index.htm

Download Android studio: https://developer.android.com/studio

Learn more about Android Studio: https://developer.android.com/studio/intro

Official Android Developer Page: https://developer.android.com/index.html

Google Developers Codelabs provide a guided, tutorial, hands-on coding experience: https://codelabs.developers.google.com/?cat=Android

Links for Contact:

GitHub: https://github.com/8426988382

Email: Tushar Tambi

References:

If You have any doubts feel free to ask in comments.

“Any comments and suggestions will be appreciated.”

--

--