BCA / B.Tech 12 min read

Working with Fragments

Unit 2 - Topic 12: Working with Fragments

What is a Fragment?

A Fragment is like a "mini-activity" within an Activity. It is a reusable portion of your app's User Interface (UI) that has its own layout and lifecycle. You can combine multiple fragments in a single activity to build a multi-pane UI.

  • Analogy: Think of an Activity as a house, and Fragments are the different rooms in that house (like a living room, kitchen). Each room has its own purpose and layout, but they are all part of the same house.

Why Use Fragments?

  • Modularity: You can break down a complex UI into smaller, more manageable parts.
  • Reusability: You can reuse the same fragment in different activities.
  • Adaptability: You can create different fragment combinations for different screen sizes. For example, on a tablet, you might show two fragments side-by-side, whereas on a phone, you might show them on separate screens.

The Fragment Lifecycle

A fragment has its own lifecycle, which is closely tied to the lifecycle of its host activity.

Key Lifecycle Methods:

  1. onAttach(): The fragment is associated with an activity.
  2. onCreate(): The fragment is initialized.
  3. onCreateView(): This method is called to create and display the fragment's UI. Here, you inflate your layout file. This is one of the most important methods.
  4. onViewCreated(): Called after `onCreateView()`, once the fragment's view has been created.
  5. onStart(): The fragment becomes visible to the user.
  6. onResume(): The fragment becomes active and interactive.
  7. onPause(): The user is navigating away from the fragment.
  8. onStop(): The fragment is no longer visible.
  9. onDestroyView(): The resources associated with the fragment's UI are cleaned up.
  10. onDestroy(): The final cleanup of the fragment is performed.
  11. onDetach(): The fragment is disassociated from the activity.

How to Create a Fragment

Creating a fragment requires two main files:

1. The Java/Kotlin Class File: This controls the fragment's logic.

Example in Java (`ExampleFragment.java`):


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

public class ExampleFragment extends Fragment {

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

2. The XML Layout File: This defines the fragment's UI.

Example (`fragment_example.xml`):


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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a Fragment"
        android:textSize="24sp" />

</LinearLayout>

How to Add a Fragment to an Activity

There are two ways to add fragments to an activity:

1. Statically (Using the XML Layout):

You can use the `` tag directly in the activity's layout file.


<!-- activity_main.xml -->
<fragment
    android:id="@+id/example_fragment"
    android:name="com.example.myapp.ExampleFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

2. Dynamically (Using Java Code):

This is the more flexible approach. You can add, remove, or replace fragments while the app is running. This is done using the `FragmentManager` and `FragmentTransaction`.

Example in Java (`MainActivity.java`):


// Inside the onCreate() method

// 1. Get the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();

// 2. Begin a FragmentTransaction
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

// 3. Create an instance of the fragment
ExampleFragment fragment = new ExampleFragment();

// 4. Add or replace the fragment
// R.id.fragment_container is a FrameLayout in the activity's layout
fragmentTransaction.replace(R.id.fragment_container, fragment);

// 5. Commit the transaction
fragmentTransaction.commit();