Is there any way to add an icon to a Snackbar?
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
.
You also can add views to SnackbarContentLayout
Kotlin code:
val snackbar = Snackbar.make(....
val textView = snackbar.view.findViewById(R.id.snackbar_action) as TextView
textView.isAllCaps = false
val imgClose = ImageView(context)
imgClose.scaleType = ImageView.ScaleType.CENTER_INSIDE
val layImageParams = ViewGroup.LayoutParams(WRAP_CONTENT, MATCH_PARENT)
imgClose.setImageResource(R.drawable.ic_close)
(textView.parent as SnackbarContentLayout).addView(imgClose, layImageParams)
imgClose.setOnClickListener { snackbar.dismiss() }
snackbar.show()
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.