Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modal Bottom sheet with FAB

I have implemented persistent bottom sheet with FAB anchored to the top of it.

bottom sheet

When I try to do the same with modal bottom sheet (extends BottomSheetDialogFragment) it says

java.lang.IllegalStateException: Could not find CoordinatorLayout descendant view to anchor view android.support.design.widget.FloatingActionButton

Is it possible to do the same layout with modal bottom sheet or maybe make a shadow and unclickable area above persistent one?

like image 389
Gleb Glazyrin Avatar asked Mar 02 '26 22:03

Gleb Glazyrin


1 Answers

I was trying to do the same "FAB on top" thing in ModalBottomSheet, but there's no direct method/way to do that.
For such cases, we therefore use FrameLayout. Inside the definition, it says that -

Child views are drawn in a stack, with the most recently added child on top.

So we can create a layout for the ModalBottomSheet (extends BottomSheetDialogFragment), which would look something like this in your case -

<FrameLayout
    android:id="@+id/parent_frame_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="wrap_content"
    android:orientation="vertical"
    tools:context=".ModalBottomSheetFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="25dp"
        android:orientation="vertical">

        <!-- Whatever layout you want to give here. This is going to be the body
        of the ModalBottomSheet. Also you might not wanna use the current Linear 
        Layout too.-->

    </LinearLayout>

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/icon_sheet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="0dp"
        android:layout_gravity="center|top"
        android:src="@drawable/ic_music"
        android:elevation="20dp"/>

</FrameLayout>

Notice that -

  1. FAB is made after LinearLayout (body for the BottomSheet), as it would be stacked over the LinearLayout.
  2. We gave a marginTop=25dp for LinearLayout but we gave marginTop=0dp for the FAB. This is how you create the half-out, half-in effect. And also gave elevation on FAB for better float look.

Finally we can inflate it's view inside the onCreateDialog overridden method and perform all necessary actions thereafter.

Hope I was able to answer your question. Do comment for any further doubts/updates.

like image 183
Krishn Agarwal Avatar answered Mar 05 '26 11:03

Krishn Agarwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!