Android M Preview for developers was released yesterday. As usual, many amazing new features are introduced. I noticed that Snackbar
is one of them.
I have read the document about Snackbar
, from which I learnt that Snackbar is in the library of Android Design Support Library, whose absolute path is android.support.design.widget.Snackbar
.
And the document says that:
Snackbars provide lightweight feedback about an operation. They show a brief message at the bottom of the screen on mobile and lower left on larger devices. Snackbars appear above all other elements on screen and only one can be displayed at a time.
They automatically disappear after a timeout or after user interaction elsewhere on the screen, particularly after interactions that summon a new surface or activity. Snackbars can be swiped off screen.
So, does Snackbar
behave like a Toast
or a Dialog
? Can Snackbars be used in a layout file? How could I use it programmatically?
P.S.:
The new Snackbar
doesn't require Android-M.
It is inside the new design support library and you can use it today.
Just update your SDK add this dependency in your code:
compile 'com.android.support:design:22.2.0'
You can use a code like this:
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null)
.show();
It is like a Toast.
To assign an action you have to set the OnClickListener
.
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", myOnClickListener)
.show();
If you would like to change the background color you can use something like this:
Snackbar snackbar = Snackbar.make(view, "Here's a Snackbar",
Snackbar.LENGTH_LONG);
View snackBarView = snackbar.getView();
snackBarView.setBackgroundColor(colorId);
snackbar.show();
If you would like to have some built-in features as the swipe-to-dismiss gesture, or the FAB scrolling up the snackbar, simply having a CoordinatorLayout
in your view hierarchy.