Looking For Anything Specific?

[Tutorial] Create Android Fragment With Kotlin Sample Code Included

Hello, my dear readers/developers,

In this tutorial, we are going to learn about android-fragments, and how to create and use android-fragments with kotlin. Before we begin what is a fragment in an android application? and here is the answer

Fragment represents a behavior or a portion of user interface in a FragmentActivity. You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a "sub activity" that you can reuse in different activities). 
Source: Android Developer Docs


Above is a small explanation about the fragment. Still didn't get a clear picture out of it, Trust me even I didn't too. But once you get the hang of it you will never lose it because there are some advantages in using fragments and one of my favorite way of using the fragment is with ViewPager and other example of Android Fragment is use it as a dialog which we covered here : How To Show Android Custom Alert Dialog Fragment. First, for now, we will create a simple application with only two programs to understand the basics of fragments. So the create a new project and at the beginning of the project, you can select the option to create fragments with the view model. But for this tutorial that is not required because ViewModel is a whole another topic, so right now we are only going to focus on the basics so start a project with an empty activity.

android application fragments basics

Steps to create fragments in android:

  • Creating a fragment is very easy in android just 
  • Right-click on your java folder
  • Click New
  • Navigate to the Fragment section
  • Select Fragment Blank


Once you have selected the Fragment (blank) you will get a dialog box to name your fragment and layout file. Name the fragment as you like. And there is one more thing you need to do in which there are two checkboxes available below the layout file name. which are "Include fragment factory methods?" and "Include interface callbacks" you can simply uncheck the boxes for now because in this tutorial we are not going to use any of the functions from the function.

You might be interested : 



What happens if you didn't uncheck the boxes? well, they will simply add some extra function to the fragment's .kt file which might be helpful when you are working with the structure of a complex fragment where you have to pass data between fragments or call a function in another fragment from one fragment or call function inactivity. Those we will do in later tutorials but for now, we will only cover the basics with two fragments to go from fragment one to fragment two.

Follow the above steps to create two fragments named "FragmentOne" and "FragmentTwo"

Android Project Structure With Two Fragments


So after creating two fragments, your android project structure will look like above, with two .kt files and XML for each fragment, you can use the same layout for both the fragments.

How to add a fragment to an activity?

At first, we have added the fragment to the activity, because as the explanation from android docs says, the fragment is a sub-activity, so it has to be in an activity we can't open a fragment directly. We must have an activity that holds the fragment so let's create a holder/container which we can use to add the fragment. open activity_main.xml and create a FrameLayout which we can use as a container for fragment and give it an id as fragmentContainer, of course, you can name it anything

activity_main.xml 

<?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">

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

</androidx.constraintlayout.widget.ConstraintLayout>

you are welcome to copy-paste the above code, but as the first rule of learning, programming is always typing even if you know the code very well.

So once we created a container with an id, we can use this container to add, replace or remove the fragments. Now open your MainActivity.kt in which we are going to add the fragment to the container so that it wouldn't show a blank page when the app starts. In order to add a fragment to a container, we are going to need a fragment manager that will help us to do some basic functionalities with the fragment, in your MainActivity.kt add this single line of code to your onCreate() method add a fragment to the container

 supportFragmentManager!!.
            beginTransaction().
            add(R.id.fragmentContainer,FragmentOne(),"FragmentOne").commit()

In the above single line of code what we actually did is that, we used a support fragment manager to begin the transaction which is adding, replacing, or removing a fragment, in our case we added the fragment to the container by-passing the first parameter as the container Id and second parameter as the fragment object and last an optional tag for the fragment, which might be useful if you're dealing with more than just two fragments so keep it in mind to add tags.  and at last, we commit the transaction so it might happen. At the beginning of my learning, I often forget to commit the transaction and so the fragment will never get added so don't forget to add .commit() at the end of the fragment manager transaction.

Recently I was writing this article on the newly introduced ActivityResult API, and when I was working with fragment found that there is a better and add a fragment to your activity, Like below, which is that we now have a new commit lambda in which we can access the fragment transaction, This piece of code will do the same as above but looks a little better to read.

  supportFragmentManager.commit {
            add(R.id.fragmentContainer,FragmentOne())
        }
  

You might be interested :


And if you're new two kotlin you might notice there is "!!" at the end of support fragment manager which is a null safe call, which means that you are certain that the support fragment manager will not be null at any point during the execution of this point of code. Below is the complete code of how your MainActivity should look like.

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        supportFragmentManager!!.
            beginTransaction().
            add(R.id.fragmentContainer,FragmentOne(),"FragmentOne").commit()

    }
}

Now, if you run the application you will see your fragment get loaded in the activity

how to create fragments in android with kotlin

How to navigate from one fragment to another?

Now that we have successfully loaded our fragment to the activity, now we can navigate to the second fragment, so if you look in the screen you will notice a button and a text but yours might not have it because we didn't get to that part actually, so now that open your  first fragments layout file which might be fragment_NAME.xml in most cases and add a button and text view

<?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"
    android:background="@color/firstFragment"
    tools:context=".FragmentOne">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/blank_fragment"
        android:textAlignment="center"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="@color/colorWhite"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/gotoButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/go_to_button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

you can refer to my above code to create and place a button, or you can follow our understanding of the basics of constraint layout tutorial to create a cool UI if you prefer


Then now open this fragment's .kt file in my case it is FragmentOne.kt, In that file we are going to get the button by its reference id and add a click listener  which will listen for clicks, and in that function, we can add the line of code to replace out FragmentOne with FragmentTwo

   val fm = fragmentManager

            fm!!.beginTransaction()
            .replace(R.id.fragmentContainer,FragmentTwo(),"FragmentTwo")
            .addToBackStack(null).commit()

Above is the line of code which will replace the "FragmentOne" with "FragmentTwo"  and if you notice that here we use fragmentManger instead of supportFragmentManager , because inside a fragment we can only get the fragmentManager, not the supportFragmentManger , which can be only accessed inside an activity. And as we are replacing the fragment so we chose to replace it instead of adding it by calling the .replace method.

You might have missed :


Also, there is one important point to consider while replacing a fragment which is addToBackStack(null), instead of null we can pass any valid string. This handles the back stack so if you want to go back to the previous screen this will come in handy, so let me explain if you did 't add this line and run your app after going to the second fragment if you click back it will close the activity instead of sending back you to the first fragment.  So in order to go back to the second screen from a fragment while clicking back, it had to be in the stack.

So now you can add this line of code into a button click in our case the goToButton, so this will be executed once the button is clicked. Refer to the complete code below

FragmentOne.kt

class FragmentOne : Fragment() {

    private lateinit var goToButton: Button

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val rootView = inflater.inflate(R.layout.fragment_blank, container, false)
        goToButton = rootView.findViewById(R.id.gotoButton)

        goToButton.setOnClickListener{
            val fm = fragmentManager

            fm!!.beginTransaction()
            .replace(R.id.fragmentContainer,FragmentTwo(),"FragmentTwo")
            .addToBackStack(null).commit()
        }
        return rootView
    }
}

findViewById in Fragment

From the above code if you see we didn't directly call the findViewById( ) method to get our button reference because in a fragment if we want to get a reference of any widgets like button, text view, or any other view we can only get the reference from the view only, which means we have to get the view by using a LayoutInflater and then get the reference from the view. Follow the above pattern for storing the views referenced in a variable then use it to get the id.

Now run your application and now you can navigate from FragmentOne to FragmentTwo.....


That's it, you have done it, thanks for reading and if you find any bugs in this article please comment below to improve a bug-free article and code.

Get the full code below:
Google Drive: Click here to download the code

So I have been trying to improve my writing, so keep checking this article for a better version and give your comments on how I can improve this article, and don't forget to subscribe. Sharing is Caring.