Featured post

Marshmallow Features Point by Point

Android Runtime (“ART”) Improved application performance and lower memory overhead for faster  multi-tasking. Battery Doze...

Thursday 4 February 2016

Android Material Design Snackbar Example

1. Simple Snackbar

Below is the syntax of a simple snackbar. The make function accepts three parameters. View, display message and duration of the message to be displayed.

Normally passing CoordinatorLayout as view param is the best option as it allows Snackbar to enable some features like swipe-to-dismiss and automatically moving of widgets like FloatingActionButton.

And the duration should be LENGTH_SHORT, LENGTH_LONG or LENGTH_INDEFINITE. When LENGTH_INDEFINITE is used, the snackbar will be displayed indefinite time and can be dismissed with swipe off.

Snackbar snackbar = Snackbar.make(coordinatorLayout, "Welcome to AndroidHive", Snackbar.LENGTH_LONG);
snackbar.show();

2. Snackbar with Action Callback

You can also mention a callback interaction method using setAction() method. This allows us to take certain action when user interacts with the snackbar.

Snackbar snackbar = Snackbar
        .make(coordinatorLayout, "Message is deleted", Snackbar.LENGTH_LONG)
        .setAction("UNDO", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar snackbar1 = Snackbar.make(coordinatorLayout, "Message is restored!", Snackbar.LENGTH_SHORT);
                snackbar1.show();
            }
        });
 snackbar.show();

3. Customizing the Snackbar View

Snackbar comes with default white color text and #323232 background color. You can override these colors as mentioned below.

Snackbar snackbar = Snackbar
        .make(coordinatorLayout, "No internet connection!", Snackbar.LENGTH_LONG)
        .setAction("RETRY", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });

// Changing message text color
snackbar.setActionTextColor(Color.RED);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();

No comments:

Post a Comment