Cody Blog

Software development

How to use Android Snackbar

I created a small toy to demo Android snackbar featrue, you can find the project on cwliu/Try_Snackbar

snackbar demo

Setup

In app build.gradle, add design support library:

dependencies {
    ...
    compile 'com.android.support:design:22.2.0'
}

Show snackbar

Just like the toast usage,

Snackbar.make(view, "Hello world",Snackbar.LENGTH_LONG).show();

Set snackbar action

snackbar.setAction("Undo", new View.OnClickListener() {
    @Override
    public void onClick(View v) {
       // Do something
    }
});

Integrate snackbar to floating action button

coordinator_layout = findViewById(R.id.coordinatorlayout);
Snackbar.make(coordinator_layout, "Hi", Snackbar.LENGTH_LONG).show();

Customize snackbar styling

In stylings.xml,

<style name="Widget.Design.Snackbar" parent="android:Widget">
    <item name="android:background">#00FF00</item>
</style>

For more styling options, couldrefer to /build/intermediates/exploded-aar/com.android.support/design/22.2.0/res/values/values.xml

Reference

- [Snackbars Google Design Guidelines](https://goo.gl/4RV4kB)
- [Snackbar Android Development Patterns S2 Ep 1)](https://www.youtube.com/watch?v=puhfMX8jb9c)

Android

Related Posts

Comments