Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
430 views
in Technique[技术] by (71.8m points)

java - Making part of a string bold in textview

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.");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...