How to add a sticky button/view in the bottom sheet dialog in android?

Well, you read the title so here is how to do it.

Create a class that extends BottomSheetDialogFragment() to create a normal bottom sheet. Now in onCreateView() initialize your layout for the bottom sheet.

Like below:

BTW make sure to create your binding variable as global on the class level.

One important note, do not add your sticky button or view which you want to add in the bottom sheet as sticky in your main bottom sheet layout file (BottomSheetLayoutBinding in this case). Just add the other stuff which you want to have in the bottom sheet whether that be recycler view or whatever the hell you want.

Now let’s add that freaking sticky view in the bottom sheet

override the onCreateDialog() function in the same file, and if you don’t want to understand the whole code just paste the below code in there (replacing layout file names with yours), and enjoy your life.

Now for the nerds who want to understand the whole truth of the universe

so, if we try to directly add any view in the bottom sheet it will always come at the end of the list, and as of now, there is no official way or so-called property to make that view appear sticky somewhere in the sheet.

So what we (I) are doing here is that we get the reference of the containerLayout which the bottom sheet internally uses and add a second child view to its parent view and with the help of layout parameters we are able to define its position in the whole dialog and not just in the visible bottom sheet

Now you might be wondering what the hell is this part for, keep wondering

In a nutshell, what this code is doing, is adding padding of the same pixels under the bottomSheetLayout which we provided to the bottomSheet in the onCreateView() method of the same height of the sticky view/button which we have added at run time so that out bottomSheetLayout is fully visible when scrolling or expending the bottom sheet to its max height.

Why the hell we can’t do it the normal way? like its just adding the freaking padding

Well, as per the geology we can not get the height/width of any view until its onDraw method has been called whether that be a view or a viewGroup so that’s why had to add this stuff to listen for the onDraw call, and once our sticky button has been drawn we get its height and set same as the bottom padding for our bottomSheetLayout (or you can set same as the bottom margin for bottomSheetLayout using layout params).

Here is a meaningless example I uploaded on GitHub if you still didn’t get the concept.

BTW you see that follow button?

Then why the hell aren’t you pressing it?

sayonara

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store