Looking For Anything Specific?

[Tutorial] BottomSheet In Android Using Kotlin With Sample Code

 In the previous article, we have learned on How to show dialogs in android, if you feel like those dialogs are not enough or kind of look like old school here is a better alternative for you,  Android BottomSheet.

You can learn about Android Bottom sheets in the documentation  [Sheet: bottom - Material Design]as it has quite a hands full of information on what to do and what not to do. In this article, we will be looking into implementing a bottom sheet in android with kotlin as a simple modal sheet and a DialogFragment - BottomSheetDialogFragment.

Bottom Sheet In Android With Kotlin:

A bottom sheet is a modal surface containing a part of useful information about a screen that is to be shown in a need to know basic information, For example, if you want to show a list of information when the user only clicks on a button or in some case where you will show a list of options to show when the user performs an action, For these use cases we will use a bottom sheet.

How To Show Bottom Sheet In Android With Kotlin:

This section will discuss how to show a layout or a part of the screen as a bottom sheet. Let's begin with designing a layout that will show a list of items for that we will be using RecyclerView you can read this article on Android RecyclerView With Kotlin for more information, After creating RecyclerView create a new layout file called list_bottom_sheet.xml which will be a constraint layout in which only we will place the RecyclerView, then there are few other attributes we need to add in order to make our constraint layout a bottom sheet, first one is we need to define the layout behavior as BottomSheetBehaviour
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
Add the above attribute to the root of our list_bottom_sheet.xml files constraint layout

Important : One common mistake people do is, we accidentally type it as behaviour but the correct spelling is behavior. Its behaviour without a 'U'

Make sure to watch out for the spelling mistake, In addition to that you can add other parameters to your need, in this example, we will be adding two more parameters to make our bottom sheet work properly and look realistic.

app:behavior_hideable="true"
    app:behavior_peekHeight="0dp"

The above two attributes are somewhat necessary, not mandatory, so what they do? behavior_hideable will allow the to the bottom sheet when dragged from the top of the sheet, and behaviour_peekHeight will allow you to make the bottom sheet visible initially without any action, this doesn't really give a realistic expression in our use case so we put that as 0dp. In your layout make sure to define the android:background as the bottom sheet layout shows a transparent background by default.

Android How To Pass Between Fragments

Now our bottom sheet is ready, there is one thing left to do which is to show them on our application, we need to add the bottom sheet layout to our activity/fragment's layout, one important thing to note here is that a bottom sheet must be a direct child of a coordinator layout,  refer the below code:

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout 
	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">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:id="@+id/showBottomSheetButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Show BottomSheet List"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

    <include
        android:id="@+id/listBottomSheet"
        layout="@layout/list_bottom_sheet"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Above is my MainActivity's layout, in here I have added the coordinator layout as the root and then included the bottom sheet layout as the direct child of the coordinator layout.

Android ActivityResult API Sample In Kotlin

BottomSheet is added to the layout now we can show it whenever the user clicks the button, for that open your main activity file, in which we will be using BottomSheetBehavior class to show and hide the bottom sheet, Refer to the below code

class MainActivity : AppCompatActivity() {

    private lateinit var bsBehavior: BottomSheetBehavior<ConstraintLayout>

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

        bsBehavior  = BottomSheetBehavior.from(findViewById(R.id.listBottomSheet))

        findViewById<Button>(R.id.showBottomSheetButton).setOnClickListener {
            bsBehavior.state = BottomSheetBehavior.STATE_EXPANDED

        }

    }
}

We start with defining a variable bsBehavior as BottomSheetBehavior and we mention this as kotlin's lateinit property mentioning that we will initialize it later, Then in the onCreate function of your activity to initialize use BottomsheetBehavior.from(View) here the View is the layout we wanted to show as a bottom sheet so that we mentioned in the variable itself as the type parameter ConstraintLayout, once initialized we can use the state of the bsBehavior to show and hide.

Initially, the bsBehavior's state will be collapsed if the peekHeight is set as "0dp", to make the bottom sheet pop up from the bottom with a click of a button, we change the state of the bottom sheet behavior to BottomSheetBehaviour.STATE_EXPANDED, here we use kotlin's setter property which will change the state of the bottom sheet, and the user can drag from the top to close the bottom sheet.

Other than BottomSheetBehavior.STATE_EXPANDED, there are two other useful states are available to set, which are STATE_COLLAPSED, STATE_HALF_EXPANDED these are the ones we normally use in most use cases,

BottomSheetBehavior.STATE_EXPANDED - to show the bottom sheet in full screen if it is in either STATE_COLLAPSED or STATE_HALF_EXPANDED

BottomSheetBehavior.STATE_HALF_EXPANDED - to show the bottom sheet only half of the screen, still the user can drag it to close or make it a full screen

BottomSheetBehavior.STATE_COLLAPSED - will hide the bottom sheet regardless of its current state.

These are some commonly used BottomSheetBehavior and there is more you can check the documentation to know more.




How To Show Bottom Sheet Dialog Fragment With Kotlin:

If you have read Dialogs With Fragment article, this would look a lot familiar because we are going to do the same approach that we did to create fragment dialogs in android.

Android SharedPreference Sample With Kotlin

The procedure is the same, first, create a new layout where you want to show a part of the information as a pop up modal sheet in your application, then create a new class, extend the class with BottomSheetDialogFragment, And use the onCreateView Method to show the layout you want as a bottom sheet. And whenever you want call show on the fragment object to show the dialog. You can refer to the below code for more details, But before that make sure you have read both Dialog Fragments in Android and Fragment Basics With Kotlin, as these will help you understand better the below code.

class BSDialogFragment : BottomSheetDialogFragment() {

    private lateinit var rootView: View

    override fun onCreateView(inflater: LayoutInflater, 
    container: ViewGroup?, 
    savedInstanceState: Bundle?)
    : View? {
        rootView = LayoutInflater.from(context)
        .inflate(R.layout.list_bottom_sheet,
        container,
        false
        )
        
        return rootView
    }



    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        rootView.findViewById<RecyclerView>(R.id.versionList).adapter = 
                AndroidVersionRecyclerAdapter(
                resources.getStringArray(R.array.android_names))

    }
}

Above is our bottom sheet dialog fragment class, we used the same layout from the above example, and now in our activity, we use the show function to display the bottom sheet on the screen.

BSDialogFragment().show(supportFragmentManager,"BSDialogFragment")

Once you have created a dialog fragment with the following above code, although did you noticed in our dialog fragment example we used onCreateDialog to create the view whereas here we are using onCreateView to create the view as a regular fragment, So then calling show on the fragment object will show the dialog as a bottom sheet, popping up from the bottom of the screen. For this tutorial, we used recyclerview to show in the bottom sheet but you can do more than that and the project sample was shared in GitHub.

I believe this was helpful, if I have missed out on something else, feel free to contact me.  Don't forget to Like My Page On Facebook And Follow On Instagram.

GitHub Link:https://github.com/blackzshaik/BottomSheetExampl

Give it a star if you like this project.


keywords:

custom bottom sheet dialog | android example

Android bottom sheet dialog transparent background

android bottom sheet half screen

android bottom sheet dialog margin

Post a Comment

0 Comments