Activity vs Fragment in Android

A comparison between these two basic Android’s UI components and how to use them properly using Kotlin

Luca Pizzini
CodeX
5 min readAug 14, 2021

--

Photo by Glen Carrie on Unsplash

Many times, reading on forums and StackOverflow, I’ve encountered people asking questions on how to correctly set up a Fragment view, or having trouble understanding the differences with Activities.

This article aims to explain what differentiates Activities and Fragments, how to correctly set them up with their respective layout, and when to use one or the other.

Let’s start with their definitions.

What is an Activity?

Just by reading the definitions of the two structures, it appears that they are very different.

According to the Android Developer’s official documentation,

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View)

What is a Fragment?

On the other hand, here is the fragment’s definition from the official documentation:

A fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must be hosted by an activity or another fragment.

The key difference, that emerges from the definitions, is that the fragment depends on an activity to exist, and so it represents only a part of the user interface.

Instead, the activity can be considered like the container under which all other UI components (fragments included) will be placed.
Without activities, there would be no user interface.

A quick note on View Binding

With the introduction of the Android Jetpack, the old way of referencing views has been updated.

Now, instead of using the findViewById method, view binding automatically generates a class that permits to reference directly all views ID in a layout.

To setup view binding in your Android application, you’ll need to specify the viewBinding flag inside your build.gradle application file:

android {
...
buildFeatures {
viewBinding true
}
}

For more information about view binding checks the official documentation.

How to set up an Activity

To correctly create and set up an Activity, you need to create a new Kotlin class, which extends the AppCompactActivity class.

A couple of file naming conventions:

  • For the layout file, specify the type of layout, followed by the name of the layout, using a snake case syntax. For example activity_main.xml.
  • For the layout class, specify the name of the layout, followed by the type of layout, using a camel case syntax. For example MainActivity.kt.

First, you’ll need to create a layout file for your activity.
Layout files in Android are XML files, and they are kept in the layout resource folder of your project.

So, create a simple activity_main.xml file and populate with a container layout (I will use a LinearLayout, just to keep things simple), along with a TextView.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

Let’s now return to our Activity class, the first step is to initialize the layout inside the onCreate method.
Then, use the setContentView method to initialize the layout which the activity will refer to.

Here is an example of a simple Activity:

private lateinit var binding: ActivityMainBindingclass MainActivity: AppCompatActivity() 
{
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
binding.textView = "This is an Activity example"
}
}

As you can see, you can refer to your TextView by using the bound layout reference.

Once you have finished your activity set up you need to declare it in your AndroidManifest.xml file, inside the <application> tag, to make the Android system aware of its existence:

<activity android:name=".MainActivity" />

If you need to specify an Activity as the starting point for your application all you’ll need to do is add two specific<intent-filter> inside your <activity> tag:

<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Once finished with the setup, your activity will be ready to be shown on the application startup.

How to set up a Fragment

To utilize fragments in your application, you will need to add the required dependencies into your project build.gradle file:

buildscript {
...

repositories {
google()
...
}
}

allprojects {
repositories {
google()
...
}
}

Once you have added the required repository, you just need to specify the AndroidX fragment library into your application build.gradle file:

dependencies {
def fragment_version = "<specify-the-latest-version>"

implementation "androidx.fragment:fragment-ktx:$fragment_version"
}

For more information on how to set up the environment correctly refer to the official documentation.

To create a Fragment, you’ll need to create a class that extends the Fragment class.

Again, I will create a simple layout file for the fragment, called fragment_main.xml, similar to the one above:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">

<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>

The layout of a Fragment is initialized in the onCreateView method:

private var _binding: FragmentMainBinding? = null
private val binding set() = _binding!!
class MainFragment: Fragment()
{
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMainBinding.inflate(inflater, container, false)
val view = binding.root
binding.textView = "This is a Fragment example" return view
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}

Unlike activities, fragments don’t need to be declared in the AndroidManifest.xml.

You may have also noticed the fact that the view binding reference is optional.
This variable is cleaned up in the onDestroyView method, once the fragment is removed from the application.
This is to avoid potential memory leaks problems, due to the fact of keeping unused object references in memory.

You will then need to add your fragment into your activity layout file, to use and show it, using a FragmentContainerView layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<androidx.fragment.app.FragmentContainerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name="com.example.MainFragment" />
<androidx.fragment.app.FragmentContainerView
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:name="com.example.Main2Fragment" />
</LinearLayout>

The FragmentContainerView will show the Fragment specified in the android:name attribute.

As you can see, you can specify multiple Fragments inside a single Activity, thanks to the modularity of the component.

Conclusion

Although activities and fragments may look similar and interchangeable at first, in reality, they are very different.

I hope that this guide will help you have a better understand and make better use of these UI components in your Android applications.

Happy coding!

--

--

Luca Pizzini
CodeX
Writer for

Software developer from Italy | Just a regular guy who loves to code and learn 💻📚 https://lucapizzini.com