Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Bold text to Android Snackbar Action Text?

We could set the color for the Action Text of Snackbar using setActionTextColor as documented in https://developer.android.com/reference/android/support/design/widget/Snackbar.html. However, is there a way to make the Text BOLD?

Thanks!!

like image 974
Elye Avatar asked Aug 26 '15 11:08

Elye


2 Answers

Use snackbar_action Resource ID.

It turns you that you can use the same method to style the Snackbar's Action text that you use to style the Snackbar's Message text.

You just have to use the Resource ID snackbar_action instead of snackbar_text.

Here's an example of setting the style for both the Message text and the Action text.

Snackbar snackbar = Snackbar.make( ... ); // Create the Snackbar however you like.

TextView snackbarActionTextView = (TextView) snackbar.getView().findViewById( android.support.design.R.id.snackbar_action );
snackbarActionTextView.setTextSize( 20 );
snackbarActionTextView.setTypeface( snackbarActionTextView.getTypeface(), Typeface.BOLD );

TextView snackbarTextView = (TextView) snackbar.getView().findViewById( android.support.design.R.id.snackbar_text );
snackbarTextView.setTextSize( 16 );
snackbarTextView.setMaxLines( 3 );

In my example, I've set the Action text to have a TextSize of 20 and a bold Typeface, and the Message text to have a TextSize of 16 and allow up to 3 lines.

like image 193
Joshua Pinter Avatar answered Sep 21 '22 19:09

Joshua Pinter


The easiest method to add BOLD text to your Snackbar text is to use the Android Html class to generate the text to pass to the Snackbar.make() function. Here is an example:

Snackbar.make(view, Html.fromHtml("Add <b>bold</b> to Snackbar text"), Snackbar.LENGTH_LONG).show();

An alternative method is to use the SpannableStringBuilder class.

SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Add ");
int boldStart = snackbarText.length();
snackbarText.append("bold");
snackbarText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), boldStart, snackbarText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
snackbarText.append(" to Snackbar text");
Snackbar.make(view, snackbarText, Snackbar.LENGTH_LONG).show();
like image 23
BrentM Avatar answered Sep 19 '22 19:09

BrentM