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.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With