Farhad ArcxX Farhad ArcxX - 2 months ago 72
Android Question

Is there anyway to add icon to 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.

Answer

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.