Introduction to Fragments | Android (original) (raw)

Last Updated : 30 Jan, 2025

**Fragment is a piece of an activity that enables a more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different layouts and their logic. You can build single-pane layouts for handsets (phones) and multi-pane layouts for tablets. You can also use fragments also to support different layouts for landscape and portrait orientation on a smartphone. The below image shows the use cases of fragments through navigations.

fragments

**Fragment Lifecycle

Android fragments have their own lifecycle very similar to an android activity.

fragment-lifecycle

**Types of Fragments

**Handling the Fragment Lifecycle

A Fragment exist in three states:

**Defining and using fragments

To define a new fragment we either extend the **android.app.Fragment class or one of its subclasses.

BlankFragment File:

Java `

package org.geeksforgeeks.demo;

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

public class BlankFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_blank, container, false); } }

Kotlin

package org.geeksforgeeks.demo

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

class BlankFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_blank, container, false) } }

`

**Fragment Transaction:

While for an dynamic activity we are set buttons for an interactive UI. If we are set after clicking the button the fragment should appear then we have to get help from Fragment Manager. It handle all the fragment in an activity. We need to set fragment transaction with the help of fragment manager and and begin transaction, and then simply replace the layout of the fragment with desired place. Below is the code that shows how to implement a fragment transaction.

MainActivity:

MainActivity.java `

package org.geeksforgeeks.demo;

import android.os.Bundle; import android.widget.Button; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

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

    Button button = findViewById(R.id.button);

    button.setOnClickListener(v -> replaceFragment(new BlankFragment()));
}

private void replaceFragment(Fragment fragment) {
    // Get fragment manager
    FragmentManager fragmentManager = getSupportFragmentManager();

    // Begin fragment transaction
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

    // Replace fragment and commit
    fragmentTransaction.replace(R.id.fragment_layout, fragment);
    fragmentTransaction.commit();
}

}

MainActivity.kt

package org.geeksforgeeks.demo

import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment

class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)

    val button = findViewById<Button>(R.id.button)
    button.setOnClickListener {
        replace(fragment = BlankFragment())
    }
}

private fun replace(fragment: Fragment) {
    // Get fragment manager
    val fragmentManager = supportFragmentManager
  
      // Begin fragment transaction
    val fragmentTransaction = fragmentManager.beginTransaction()
    
    // Replace fragment and commit
    fragmentTransaction.replace(R.id.fragment_layout, fragment)
    fragmentTransaction.commit()
}

}

`

activity_main.xml:

activity_main.xml `

<androidx.constraintlayout.widget.ConstraintLayout 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:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/white" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity">

<FrameLayout
    android:id="@+id/fragment_layout"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_margin="24dp"
    app:layout_constraintBottom_toTopOf="@+id/textView"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="24dp"
    android:text="This is MainActivity"
    android:textColor="@color/black"
    android:textSize="24sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toTopOf="@+id/button"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="32dp"
    android:backgroundTint="@color/green"
    android:text="Switch"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

`

fragment_blank.xml:

fragment_blank.xml `

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textColor="@color/white"
    android:gravity="center"
    android:text="@string/hello_blank_fragment" />

`

Output: