• Post author:
  • Post category:Android
  • Reading time:20 mins read

Have you been scouring through the internet to find a simple Android Fragments Implementation Example to get you started quickly? Congratulations, you’ve found it.

fragment is a small piece that’s come off a larger whole, and to fragment is to break.

www.vocabulary.com/dictionary/fragment

What are Android Fragments?

Android Fragments are the components of an Activity with their own layout and behavior which makes them very useful for making flexible UI. It is like a simple version of an Activity with its own lifecycle methods like onCreate()onStart()onPause(), and onStop(). An Activity can be made up of multiple Fragments. You can use Fragments when you want to show multiple screens with their own independent layouts and kotlin/java code, in a single Activity.

Shown below is one of the use cases of Fragments to show different screens for each tab.

Fragments should be self contained to ensure reusability.

If you are in a hurry and don’t wanna go through the example, check out the Conclusions in the end. But the best way to learn Android Fragments, is by making an Android Fragment Example App. So lets do it.

Android Fragment Example App

Fragments Example App

In this Android fragment example app, we’ll have a single Activity and 3 Fragments. We’ll learn:

  1. How to set up fragments.
  2. How to navigate to a particular fragment.
  3. How to send parameters to a fragment.

We’ll design the activity_main layout like this:
At the top we’ll have an EditText widget and a Button, in the middle we’ll have a reserved area where we’ll put the fragments and at the bottom we’ll have 3 Buttons. The Home Button brings the Home fragment in the middle area, the Profile button brings the Profile fragment and the Settings button brings the Setting fragment on click.

In the top EditText, we’ll put some text and when we click the Send to Profile button, it will open the Profile fragment with this text as an argument. we’ll use this argument to display text in TextView.

Setting Up the Project

Alright, now create a new Android Studio project with Blank Activity. If you don’t know how to do this, check out this post here. Once you are done, you should have your activity_main.xml and MainActivity.kt files like this.

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.fragmentsexample

//bunch of import statements
import ...

class MainActivity : AppCompatActivity() {

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

    }
}

Alright, now let’s create the activity_main.xml layout like we stated above. Go to the activity_main.xml file and put the below code there. It is a very simple layout which I don’t think needs any explanation. However, if you do face any difficulty here, please mention it in the comments. The only thing to note here is that we’re using the FrameLayout to reserve the space where the Fragments will be later. Please keep a note of the IDs of all Buttons, EditText and TextViews. We’ll need them later to reference these widgets from our kotlin code.

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

    <Button
        android:id="@+id/home_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/profile_btn"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent" />

    <Button
        android:id="@+id/profile_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Profile"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/setting_btn"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/home_btn" />

    <EditText
        android:id="@+id/enter_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="Enter Name"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toStartOf="@+id/send_to_profile_button"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/send_to_profile_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Send to Profile"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/enter_name"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/setting_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Settings"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/profile_btn" />

    <FrameLayout
        android:id="@+id/body_fragment"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toTopOf="@+id/profile_btn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/enter_name">

    </FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>

Setting Up Fragments

Go to File > New > Fragment > Fragment(Blank) and create a new fragment. Name it HomeFragment.

Open the fragment_home.xml file and put this code there.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/home_constraint_layout"
    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"
    android:background="#59ED24"
    tools:context=".HomeFragment">

    <Button
        android:id="@+id/homepage_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@+id/home_textView"
        app:layout_constraintStart_toStartOf="@+id/home_textView"
        app:layout_constraintTop_toBottomOf="@+id/home_textView" />

    <TextView
        android:id="@+id/home_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home Fragment"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/homepage_button"
        app:layout_constraintEnd_toEndOf="@id/home_constraint_layout"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="@id/home_constraint_layout"
        app:layout_constraintTop_toTopOf="@id/home_constraint_layout" />

</androidx.constraintlayout.widget.ConstraintLayout>

Now open the HomeFragment.kt file. We’ll delete the extra stuff and at the end it should look something like this.

package com.example.fragmentsexample

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

class HomeFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_home, container, false)
    }

}

Since we’ve put a Button in the Home Fragment layout, we’ll add an onClickListener to it which’ll just display a Toast message on click. To do that, add the Fragment’s OnViewCreated lifecycle method below the onCreateView method. OnViewCreated is called immediately after onCreateView and initializations should be done here and not in onCreateView. Please note that we have to write view.findViewById and not findViewById directly.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val homePageBtn: Button = view.findViewById(R.id.homepage_button)
        homePageBtn.setOnClickListener {
            Toast.makeText(
                context,
                "Home Page Button clicked!",
                Toast.LENGTH_SHORT).show()
        }
    }

Let’s create two new Fragments for the Profile and Setting screen.

<?xml version="1.0" encoding="utf-8"?>
<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/profile_constraint_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#4AE4D2"
    tools:context=".ProfileFragment">


    <TextView
        android:id="@+id/profile_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Profile Fragment"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="@id/profile_constraint_layout"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="@id/profile_constraint_layout"
        app:layout_constraintTop_toBottomOf="@+id/imageView2" />

    <Button
        android:id="@+id/profilepage_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="@+id/imageView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toEndOf="@+id/imageView2" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="112dp"
        android:layout_height="140dp"
        android:src="@drawable/dp"
        app:layout_constraintBottom_toTopOf="@+id/profile_textView"
        app:layout_constraintEnd_toStartOf="@+id/profilepage_button"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/profileNameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Name"
        android:textColor="#000000"
        android:textSize="25sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toTopOf="@+id/profilepage_button"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView2"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.fragmentsexample

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast


class ProfileFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_profile, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val profilePageBtn: Button = view.findViewById(R.id.profilepage_button)
        profilePageBtn.setOnClickListener {
            Toast.makeText(
                context,
                "Profile Page Button clicked!",
                Toast.LENGTH_SHORT).show()
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:id="@+id/setting_constraint_layout"
    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"
    android:background="#C54D4D"
    tools:context=".SettingFragment">


    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="50dp"
        android:layout_marginBottom="50dp"
        android:clickable="true"
        android:src="@android:drawable/ic_menu_edit"
        app:backgroundTint="#FFFFFF"
        app:layout_constraintBottom_toBottomOf="@id/setting_constraint_layout"
        app:layout_constraintEnd_toEndOf="@id/setting_constraint_layout" />

    <TextView
        android:id="@+id/settings_textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Settings Page"
        android:textSize="40sp"
        app:layout_constraintBottom_toBottomOf="@id/setting_constraint_layout"
        app:layout_constraintEnd_toEndOf="@id/setting_constraint_layout"
        app:layout_constraintStart_toStartOf="@id/setting_constraint_layout"
        app:layout_constraintTop_toTopOf="@id/setting_constraint_layout" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.example.fragmentsexample

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import com.google.android.material.floatingactionbutton.FloatingActionButton

class SettingFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_setting, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val settingPageButton: FloatingActionButton = view.findViewById(R.id.floatingActionButton)
        settingPageButton.setOnClickListener {
            Toast.makeText(
                context,
                "Setting Button clicked!",
                Toast.LENGTH_SHORT).show()
        }
    }
}

Okay, now we have all the layouts and fragments in place. It is time to hook them up to the main layout.

Navigating to Fragments

Now go to the MainActivity.kt file and put the following code inside onCreate() below the setContentView() method.

We’ll first get references to the navigation Buttons.

val homeBtn: Button = findViewById(R.id.home_btn)
val profileBtn: Button = findViewById(R.id.profile_btn)
val settingBtn: Button = findViewById(R.id.setting_btn)

Next, we get an instance of our fragments.

val homeFragment = HomeFragment()
val profileFragment = ProfileFragment()
val settingFragment = SettingFragment()

Using supportFragmentManager, we replace the FrameLayout, which has the ID body_fragment, with homeFragment so that when the UI is rendered for the first time, it has the Home Fragment there.

supportFragmentManager.beginTransaction().apply {
    replace(R.id.body_fragment, homeFragment)
    commit()
}

Next we setOnClickListener for the 3 nav Buttons, so that on click, they open those particular fragments.

homeBtn.setOnClickListener {
    supportFragmentManager.beginTransaction().apply {
        replace(R.id.body_fragment, homeFragment)
        commit()
    }
}

profileBtn.setOnClickListener {
    supportFragmentManager.beginTransaction().apply {
         replace(R.id.body_fragment, profileFragment)
         commit()
    }
}

settingBtn.setOnClickListener {
    supportFragmentManager.beginTransaction().apply {
        replace(R.id.body_fragment, settingFragment)
        commit()
    }
}

Alright, we can now open different fragments in our activity. Now lets see how to pass arguments to them.

Passing Arguments To Fragment

Still in the MainActivity.kt file, now we need to get references to the EditText and Send To Profile Button at the top section of the activity_main layout.

val sendToProfileButton: Button = findViewById(R.id.send_to_profile_button)
val enterNameEditText: EditText = findViewById(R.id.enter_name)

We’ll enter some name in the EditText input area and when we click the Send To Profile Button, it’ll open the Profile Fragment with this name displayed in a TextView.

sendToProfileButton.setOnClickListener {
            val input_name: String = enterNameEditText.editableText.toString()
            val args = Bundle()
            args.putString("name", input_name)
            profileFragment.arguments = args
            supportFragmentManager.beginTransaction().apply {
                replace(R.id.body_fragment, profileFragment)
                commit()
            }
        }

And there you have it guys. Please feel free to comment if you have any queries or if I’ve made some mistakes here. So, the main Points are the following.

Conclusions

  1. Set up FrameLayout in the activity layout where you want to put the fragments.
  2. Instantiate your fragments in the Activity kotlin/java code.
  3. use supportFragmentManager to replace the FrameLayout with the Fragment you want like this:
supportFragmentManager.beginTransaction().apply {
        replace(R.id.id_of_frame_layout, yourFragment)
        commit()
    }

4. To open fragment with some arguments:

  1. First create a Bundle(): val args = Bundle()
  2. Put argument in bundle: args.putString("arg_key", arg_value)
  3. Set this bundle to your fragment’s arguments: yourFragment.arguments = args
  4. Then call supportFragmentManager like above.

Thank you guys for checking out this tutorial. Please do comment for any queries. Have fun.