NiceToMytyuk
NiceToMytyuk

Reputation: 4277

How to anchor FAB to BottomSheet with margins?

I have an issue in my APP, I have a BottomSheet and I was adding a FAB, the FAB should be always at the top of the BottomSheet so I have added a bottom margin to the FAB, the issue is that once the BottomSheet is expanded the FAB goes anchored to bottomsheet without the initial bottom margin.

How could I achieve the FAB to be always at the top?

Here is my code:

<androidx.coordinatorlayout.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="2dp"
        android:padding="2dp"
        android:scrollbars="vertical"
        tools:listitem="@layout/recyclerview_pterm" />

    <include
        layout="@layout/bottom_sheet_pterm" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="76dp"
        android:clickable="true"
        android:focusable="true"
        app:layout_anchor="@+id/bottomSheet"
        app:layout_anchorGravity="top|end"
        app:srcCompat="@drawable/ic_covid"
        android:contentDescription="@string/verifica_gp" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

And here is how it looks like:

enter image description here

Upvotes: 2

Views: 1005

Answers (1)

Zain
Zain

Reputation: 40830

You can solve that by adding these two attributes to the FAB:

<com.google.android.material.floatingactionbutton.FloatingActionButton
    ....
    app:useCompatPadding="true"
    android:layout_gravity="top" />

The android:layout_gravity="top" makes the FAB to be on top of the anchor (i.e. not intersected with it), and app:useCompatPadding="true" Allows the padding between the FAB & The anchor (i.e. bottomSheet).

Sample:

Upvotes: 4

Related Questions