Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Snackbar from dismissing on action click

How to prevent Android Snackbar from dismissing on setAction onclick, Thanks

Snackbar.make(rootlayout, "Hello SnackBar!", Snackbar.LENGTH_INDEFINITE)
   .setAction("Undo", new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           // Snackbar should not dismiss
       }
   })
   .show();
like image 319
Eleazer Toluan Avatar asked Oct 18 '16 08:10

Eleazer Toluan


People also ask

What are the different ways to achieve snack bar dismissal?

setAction("Dismiss", new View. OnClickListener() { @Override public void onClick(View v) { } }). show(); The snackbar can be dismissed by a swipe.

How do you hide snackbar in flutter?

You can hide the current SnackBar before the end of its duration by using: ScaffoldMessenger. of(ctx). hideCurrentSnackBar();

How do you dismiss indefinite snackbar?

use dismiss() to close a snackbar programatically.

What is a snackbar in Android?

Snackbar in android is a new widget introduced with the Material Design library as a replacement of a Toast. Android Snackbar is light-weight widget and they are used to show messages in the bottom of the application with swiping enabled. Snackbar android widget may contain an optional action button.


1 Answers

Here is a somewhat cleaner solution for achieving this, which doesn't require reflection. It's based on knowning the view ID of the button within the Snackbar. This is working with version 27.1.1 of the support library, but may no longer work in a future version if the view ID will be changed!

First, set your snackbar action using an empty OnClickListener:

snackbar.setAction("Save", new View.OnClickListener() {
    @Override
    public void onClick(View v) {}
});

Afterwards, add a callback to the snackbar (before showing it). Override the onShown function, find the button using R.id.snackbar_action and add your own OnClickListener to it. The snackbar will only be dismissed when manually calling snackbar.dismiss(), or by swiping if the snackbar is attached to a CoordinatorLayout (how to disable the swipe is a different SO question).

snackbar.addCallback(new BaseTransientBottomBar.BaseCallback<Snackbar>() {
    @Override
    public void onShown(Snackbar transientBottomBar) {
        super.onShown(transientBottomBar);

        transientBottomBar.getView().findViewById(R.id.snackbar_action).setOnClickListener(new View.OnClickListener() {
            // your code here
        }
like image 81
Ovidiu Avatar answered Oct 08 '22 20:10

Ovidiu