TheJadav

Android Fragment Example – Work with fragment in android

Fragment is light part of activity, It can be added as element of activity or we can show it as dialog also. Android suggest to use fragment to divide UI. It is also separating our UI code. Let's make activity first. In activity define FrameLayout, which will manage your fragment:

Fragment

Fragment is light part of activity, It can be added as element of activity or we can show it as dialog also. Android suggest to use fragment to divide UI. It is also separating our UI code.
Let’s make activity first. In activity define FrameLayout, which will manage your fragment:

FrameLayout

        <FrameLayout
        android:id="@+id/flBase"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

Fragment

class BaseFragment : Fragment(layoutId) {
}

Replace Fragment

Add below method in Activity to replace fragment.

    fun replaceFragment(fragment: Fragment){
        val ft = supportFragmentManager.beginTransaction()
        ft.replace(R.id.flBase, fragment)
        ft.commit()
    }

    // Call this replaceFragment to add fragment
    replaceFragment(BaseFragment())

    //add this method before commit, to add fragment to backstack
    ft.addToBackStack(null);

    //To add fragment above current fragment you can also use "add" instead of "replace"

This method will replace your existing fragment with new fragment. Fragment have also feature like backstack to manage back button press to go to previous fragment.

Share this content:

Share:

More Posts

Introduction to Kotlin: A Versatile and Modern Programming Language

Kotlin, a versatile and modern programming language, offers developers a concise, safe, and interoperable coding experience. With features like null safety, extension functions, and coroutines, Kotlin enhances productivity and readability, making it an attractive choice for Android development and beyond. Whether you’re new to programming or an experienced developer, exploring Kotlin opens up a world of possibilities for building robust and expressive applications.

Mastering the Android Activity Lifecycle: A Comprehensive Guide

The Android Activity Lifecycle is a fundamental concept for Android developers. It defines how an Activity behaves during its lifecycle, from creation to destruction. Understanding the Activity Lifecycle is crucial for managing resources efficiently and delivering a smooth user experience. In this blog post, we’ll briefly introduce the different states an Activity can be in and the main callback methods associated with each state. Let’s dive in and explore this important aspect of Android app development!

Table of Contents

Send Us A Message