So, you think that know how to use Snackbar and FAB? You know nothing!

Maybe you got used to using Snackbar on views with List and Floating Action Button. You wrapped everything with CooridnatorLayout and watched shiny animation where FAB was moved up when Snackbar was shown. This looked good, and you were happy. But not anymore!

Some time ago Google changed how Snackbar and FAB should behave together. Now Snacbar should be shown above FAB!


You can read more about it here:
https://material.io/components/snackbars#placement

How to achieve it? It’s still easy. Instead of CoordinatorLayout wrap everything with ConstraintLayout and set setAnchorView for Snackbar.

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/rootLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include
            layout="@layout/recycler_view_fragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/fabButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
Snackbar.make(rootLayout, TEXT_TO_SHOWN, DURATION_TIME)
  .setAnchorView(fabButton)

Now you are ready to use Snackbar with Floating Action Button according to Google Material guidelines.

See you on The Code Side!
All the best,
Artur

Add a Comment

Your email address will not be published.