Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making part of a string bold in textview

Tags:

java

android

Why is the following code not working? It works in a Toast but not in a TextView. boldName doesn't show up as bold when I run my program but it does show up as bold when I set it to a Toast. Does anyone have any other solutions?

String boldName = "<b>" + name + "</b>";
Spanned conBold = Html.fromHtml(boldName);
chosen_contact.setText("You have chosen " + conBold + " as your contact.");
like image 307
user3131263 Avatar asked Dec 31 '13 02:12

user3131263


People also ask

How do I make part of a string bold?

android:textStyle attribute is the first and one of the best way to make the text in TextView bold. just use “bold”. If you want to use bold and italic. Use pipeline symbol “|” .

How do I make text bold in TextView?

Change Text Style of TextView to BOLD in XML Layout File textStyle attribute of TextView widget accepts on of these values: "bold" , "italic" or "normal" . To change the style to bold, you have to assign textStyle with "bold" .

How do I make part of a string bold in Java?

16 + names. length() is where to stop bolding. So I said start bolding after "You have chosen " and stop bolding the length of the name positions after where it started. b is the type of span to apply on the StringBuilder (which is bold).

How do I make Spannable strings bold?

SpannableString string = new SpannableString("Bold and italic text"); string. setSpan(new StyleSpan(Typeface. BOLD), 0, 4, Spannable.


1 Answers

I'm honestly not sure why exactly TextViews act the way they do where you can set it all bold as you are doing, but only if they entire TextView is bold, yet you can't if only part of it is bold and there are other Strings in there.

However, this code will work for you:

// a SpannableStringBuilder containing text to display
SpannableStringBuilder sb = new SpannableStringBuilder("You have chosen " + name + " as your contact.");

// create a bold StyleSpan to be used on the SpannableStringBuilder
StyleSpan b = new StyleSpan(android.graphics.Typeface.BOLD); // Span to make text bold

// set only the name part of the SpannableStringBuilder to be bold --> 16, 16 + name.length()
sb.setSpan(b, 16, 16 + name.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); // make first 4 characters Bold

chosen_contact.setText(sb); // set the TextView to be the SpannableStringBuilder
like image 81
Michael Yaworski Avatar answered Oct 05 '22 23:10

Michael Yaworski