Fragments in Android Kotlin

Satheesh Guduri
2 min readDec 28, 2021

Hello All, In this article we will see what is the fragment and how to add to the activity.

Fragment is just like an activity, but the difference is we can add the fragment in to the activity, it means we can divide the activity in to multiple fragments.

For, example we have two layouts in the layout file, here these two layouts are linked to one activity, instead of second layout we can add fragment, the difference is — it is independent just like activity.

Suppose, if you have an activity with two fragments like below.

Now, we have One Activity with two fragments, if you click on the button of first fragment it is having its own lifecycle just like main activity.

Adding Fragment:

First step, in your main layout file you have to provide some space to add the fragment like below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">

<Button
android:id="@+id/btn_show"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="show"/>

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

</FrameLayout>
</LinearLayout>

Here, fragment_main layout is used to show the fragment, now lets see how can we add the fragment to activity.

val fram = supportFragmentManager.beginTransaction()
fram.add(R.id.fragment_main, fragment)
fram.commit()

Now, simple create the new blank fragment like activity and after that there is supportFragmentManager which is used to add the fragment like above.

Just like add you can replace and remove the fragments like below.

val fram = supportFragmentManager.beginTransaction()
fram.replace(R.id.fragment_main, fragment)
fram.commit()

If you are adding fragment in another fragment then user fragmentmanager like below

val fram = fragmentManager.beginTransaction()
fram.replace(R.id.fragment_main, fragment)
fram.commit()

Thanks for reading this article, if you like my article please clap for me.

--

--