Search code examples
androidandroid-snackbar

Is there any way to add an icon to a Snackbar?


This is my Snackbar code :

        Snackbar.make(viewHolder.productView, "Some Text Here ..", Snackbar.LENGTH_SHORT)
                .setAction("I want be a icon here instead TEXT", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // Perform anything for the action selected
                    }
                })
                .show();

Is there anyway to add icon instead of text in .setAction ?

I know google suggested not use icon in Snackbar, but I want to use it.


Solution

  • ImageSpan may not look right with longer text (multiple lines). Instead, use a left compound drawable (same as android:drawableLeft).

    Snackbar snackbar = Snackbar.make(layout, R.string.test, Snackbar.LENGTH_LONG);
    View snackbarLayout = snackbar.getView();
    TextView textView = (TextView)snackbarLayout.findViewById(android.support.design.R.id.snackbar_text);
    textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.white_checkbox, 0, 0, 0);
    textView.setCompoundDrawablePadding(getResources().getDimensionPixelOffset(R.dimen.snackbar_icon_padding));
    snackbar.show();
    

    If you are using the AndroidX Material library, replace android.support.design.R.id.snackbar_text with com.google.android.material.R.id.snackbar_text.