-2

I display a snackbar using the code

Snackbar.make(rootView, mMessage, Snackbar.LENGTH_LONG)
                .make(rootView, mMessage, Snackbar.LENGTH_INDEFINITE)
                .setAction("Action", null)
                .show();

This snackbar is kept displayed on screen

What I am trying to do:

  • Once it is kept displayed on screen, How to dismiss it when i click on a view which is different from snackbar action button
  • Is it possible
Devrath
  • 42,072
  • 54
  • 195
  • 297
  • Did you try using `dismiss` method on the snackbar object? Of course first save the reference to the snackbar rather than call `show` on it immediately. – Vucko Jul 15 '19 at 09:51
  • try keeping a reference to your snackbar by assigning it to a local variable and call dismiss from that variable – a_local_nobody Jul 15 '19 at 09:52

4 Answers4

0

You can do this by keeping a reference to that snackbar instance:

val snackbar = Snackbar.make(rootView, mMessage, Snackbar.LENGTH_LONG)
                .make(rootView, mMessage, Snackbar.LENGTH_INDEFINITE)
                .setAction("Action", null)
                .show();

Now whenever you want to dismiss it just call .dismiss(), so in your case:

theOtherButton.setOnClickListener { snackbar.dismiss() }
Joaquim Ley
  • 4,038
  • 2
  • 24
  • 42
  • val is kotlin, not java :) – a_local_nobody Jul 15 '19 at 09:55
  • So? Where does the question show if it is Java or Kotlin? ^^ – Joaquim Ley Jul 15 '19 at 13:32
  • it has a semicolon at ````.show();```` haha but i don't blame you, i've been doing kotlin for so long now that answering stuff in java is almost impossible :) – a_local_nobody Jul 15 '19 at 13:33
  • ';' are allowed in Kotlin hehe. But this -> https://techcrunch.com/2019/05/07/kotlin-is-now-googles-preferred-language-for-android-app-development/?guccounter=1&guce_referrer_us=aHR0cHM6Ly93d3cuZ29vZ2xlLmNvbS8&guce_referrer_cs=Oi1dYknjQto4xZVtYYztZA motivates me to post in Kotlin (also I don't use Java in my day to day work hehe) – Joaquim Ley Jul 15 '19 at 15:31
  • i agree that the semicolons are allowed in kotlin, but most people learn to remove them, also, OP has posted various other questions in java, but really we are just arguing for nothing at this point :) i do agree with your answer either way though :) – a_local_nobody Jul 15 '19 at 15:33
0
mySnackbar = Snackbar.make(rootView, mMessage, Snackbar.LENGTH_LONG)
                .make(rootView, mMessage, Snackbar.LENGTH_INDEFINITE)
                .setAction("Action", null);
mySnackbar.show();

After this just do (in other view's onClickListener):

mySnackbar.dismiss();
Vucko
  • 7,371
  • 2
  • 27
  • 45
0

Just Use yourSnackbar.dismiss();

shubh gaikwad
  • 127
  • 2
  • 10
0

You can surround with InkWell as:

SnackBar(
  content: InkWell(
    onTap: () {ScaffoldMessenger.of(context).hideCurrentSnackBar();},
hiDemo Studio
  • 91
  • 1
  • 4