Tech tip of this week

Android: Snack Bar example

Google released Snackbar component in Android Design support library.

Snackbars are just like Toast messages except they provide action to interact with. Snackbar will be displayed at the bottom of the screen and they automatically time out after the given time length by animating off the screen. In addition, users can swipe them away before the timeout.


Sample code to use Snackbar:

1) add design support library in build.gradle
    compile 'com.android.support:design:22.2.0'

2) Simple Snack Bar:
      Snackbar snackbar = Snackbar.make(coordinatorLayout, "Welcome" ,                                                 Snackbar.LENGTH_LONG);
      snackbar.show();

3) Snack Bar with Action:

    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();

4) Customize Snack Bar:
      Snackbar snackbar = Snackbar
        .make(coordinatorLayout, "Welcome", 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 view= snackbar.getView();
      TextView textView = (TextView)                                                                       view.findViewById(android.support.design.R.id.snackbar_text);
      textView.setTextColor(Color.YELLOW);
      snackbar.show();

No comments:

Post a Comment