Step 5: Understanding Fragments in Android - Modular and Flexible UI Design

Mastering Fragments: Building Dynamic and Modular UIs in Android

Welcome to Step 5 of your Android development journey! In the previous step, you learned about Intents and how they facilitate communication between Activities. However, managing multiple Activities can become cumbersome, especially when designing complex UIs. This is where Fragments come in!

Fragments in Android
fragments in Android


In this guide, we’ll explore Fragments, why they are useful, and how to implement them effectively with real-world examples.

What Are Fragments?

A Fragment is a reusable, self-contained piece of UI that can be embedded within an Activity. Unlike Activities, Fragments don’t exist independently; they are always hosted inside an Activity.

Why Use Fragments?

  • Reusability: Use the same Fragment across multiple Activities.
  • Flexibility: Adapt UIs dynamically for different screen sizes (phones, tablets).
  • Modularity: Separate logic into independent, manageable components.
  • Efficiency: Reduce unnecessary Activity transitions, improving performance.

Understanding the Fragment Lifecycle in Android Development

Fragments are like the superheroes of Android apps—small, powerful, and ready to save the day. But to unlock their full potential, you need to understand their lifecycle.

Think of it like a rollercoaster: they get created, do some cool stuff, and then clean up before the next adventure. Understanding this process makes your app smoother and faster. So, before diving into creating fragments, let’s explore the essential stages of a Fragment’s lifecycle!


Fragment Lifecycle states and their relation to both the fragment's lifecycle callbacks and the fragment's view Lifecycle.

Overview of Fragment Lifecycle Methods in Android

Like an activity, a fragment follows a lifecycle with a few additional states. Here’s a step-by-step look at each stage:

1. onAttach(Context) → The Beginning

  • The fragment gets attached to its host activity. At this point, it gains access to the activity's context.

2. onCreate(Bundle?) → Initialization Time

  • This is where the fragment gets created. Use this method to set up essential components like variables and data that persist across fragment recreation.

3. onCreateView(LayoutInflater, ViewGroup?, Bundle?) → Building the UI

  • Here, the fragment creates and returns its UI layout. You inflate the XML file for the fragment's view in this method.

4. onViewCreated(View, Bundle?) → View is Ready

  • Now the fragment’s view is fully created. This is a great place to initialize UI components or set up observers.

5. onStart() → Becoming Visible

  • The fragment is now visible to the user, though it might not be in the foreground yet.

6. onResume() → Fully Interactive

  • At this stage, the fragment is active and the user can interact with it. This is where animations, real-time updates, or event listeners should be handled.

7. onPause() → Preparing to Go Offscreen

  • The fragment is no longer in focus but is still partially visible. Use this method to pause animations or stop any updates that aren’t needed when the user isn’t fully engaged.

8. onStop() → No Longer Visible

  • The fragment is completely hidden. Any heavy processes like network calls should be stopped here to avoid resource leaks.

9. onDestroyView() → Cleaning Up UI

  • The fragment’s view is removed. If you stored references to UI components, clean them up to avoid memory leaks.

10. onDestroy() → Saying Goodbye

  • The fragment instance is being destroyed. If you have background tasks running, cancel them here.

11. onDetach() → Completely Gone

  • The fragment is detached from the activity. It no longer has access to the activity's context.

Here's an example of how to log lifecycle events in a Fragment:

class FirstFragment : Fragment() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("FragmentLifecycle", "onCreate called")
    }
    
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        Log.d("FragmentLifecycle", "onCreateView called")
        return inflater.inflate(R.layout.fragment_first, container, false)
    }

    override fun onStart() {
        super.onStart()
        Log.d("FragmentLifecycle", "onStart called")
    }
}

Now, when running the app, these logs will appear in Logcat, helping to track the Fragment’s lifecycle stages.


Why Should You Care about Fragment Lifecycle?

Understanding these lifecycle methods helps you:

  • Prevent memory leaks by properly cleaning up resources
  • Improve performance by stopping unnecessary tasks when the fragment isn’t visible
  • Handle configuration changes like screen rotations effectively



Creating a Basic Fragment

Let’s create a simple Fragment and add it to an Activity.

Step 1: Create a New Fragment

  1. In Android Studio, go to File > New > Fragment > Blank Fragment.
  2. Name it FirstFragment.kt.
  3. Android Studio will generate a layout file (fragment_first.xml) and a Kotlin file (FirstFragment.kt).

Step 2: Define the Fragment Layout (fragment_first.xml)

<?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:orientation="vertical">

    <TextView
        android:id="@+id/fragmentText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello from Fragment!"/>
</LinearLayout>

Step 3: Define the Fragment Class (FirstFragment.kt)

package com.example.myapp

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment

class FirstFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        Log.d("FragmentLifecycle", "onCreateView called")
        return inflater.inflate(R.layout.fragment_first, container, false)
    }
}

Step 4: Add the Fragment to an Activity (activity_main.xml)

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

Step 5: Load the Fragment in MainActivity.kt

package com.example.myapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        // Load the FirstFragment into the container
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, FirstFragment())
            .commit()
    }
}

Now, when you run the app, FirstFragment will be displayed inside MainActivity.


What’s Next?

In the next step, we’ll explore RecyclerView, a powerful way to display lists efficiently in Android apps. Stay tuned, and don’t forget to subscribe for updates! Have questions? Drop them in the comments below.


Stay Tuned! Don’t forget to subscribe and follow for the next steps in this series. Got questions? Drop them in the comments below—I’m here to help!

Let’s get coding and bring your app ideas to life!

Pragnesh Ghoda

A forward-thinking developer offering more than 8 years of experience building, integrating, and supporting android applications for mobile and tablet devices on the Android platform. Talks about #kotlin and #android

Post a Comment

Please let us know about any concerns or query.

Previous Post Next Post

Contact Form