Change Snackbar Position When Bottom App Bar or Bottom Navigation View Is Present

The SnackBar is mainly used to provide feedback to the user and it is shown at the bottom of the screen. This UI element is used alongside Toast or as a replacement in some application.

We typically show snack message as follows.

// Show snack message
Snackbar.make(binding.coordinatorLayout, message, LENGTH_SHORT)
        .show();

This works well as long as the screen does not contain the Bottom App Bar or the Bottom Navigation View. When we have the specified elements the Snack Message overlaps on the Bottom App Bar or ends up behind the Bottom Navigation View.

This behavior is shown in the images below.

snack-message-overlapped-bottom-app-bar

To avoid such behavior we need to use setAnchorView method and pass id of a view. The Snack Message is shown on top of the view element with the specified id.

// Show snack message
Snackbar.make(binding.coordinatorLayout, message, LENGTH_SHORT)
        .setAnchorView(binding.fab)
        .show();

snack-message-bottom-app-bar-correct-position

Similarly, when Bottom Navigation View or Floating Action Button id is passed to setAnchorView method, the Snack Message corrects and shows on top, as shown in the below pictures.

snack-message-bottom-navigation-view

snack-message-fab

Anchoring to Floating Action Button is not necessary when the Floating Action Button is visible in isolation at the bottom of the screen. The Snack Message pushes the Floating Action Button up and makes itself visible at the bottom of the screen. But if you want to show the message on top similar to Bottom Navigation View or Bottom App Bar then we can anchor the Floating Action Button.

Popular posts from this blog

How to Read Metadata from AndriodManifest File

Add Spacing to Recycler View Linear Layout Manager Using Item Decoration

Create Assets Folder, Add Files and Read Data From It

Add Options Menu to Activity and Fragment

How to Set an Android App as a Default Dialer