Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 972
Farhad Navayazdan Avatar asked Jul 08 '15 06:07

Farhad Navayazdan


People also ask

How do I add icons to Snackbar?

If you want to add an icon to the right of a snackbar, you need to do the following: SpannableStringBuilder buildetTextRight = new SpannableStringBuilder(); buildetTextRight. append(" "); buildetTextRight. setSpan(new ImageSpan(context, R.


2 Answers

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.

like image 109
Daniel Zolnai Avatar answered Sep 21 '22 09:09

Daniel Zolnai


Have you heard of ImageSpan? It may help you you to achieve your goal! See below code:

SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append("My message ").append(" "); builder.setSpan(new ImageSpan(MainActivity.this, R.drawable.ic_launcher), builder.length() - 1, builder.length(), 0); builder.append(" next message"); Snackbar.make(parent view, builder, Snackbar.LENGTH_LONG).show();] 

Dont use big icons as they will not maintain gravity.

Ref:How to display image in Android's TextView?

Hope it helped.

like image 24
Harry's Lab Avatar answered Sep 20 '22 09:09

Harry's Lab