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

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message