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 t
Solution 1:
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 displaySpannableStringBuildersb=newSpannableStringBuilder("You have chosen " + name + " as your contact.");
// create a bold StyleSpan to be used on the SpannableStringBuilderStyleSpanb=newStyleSpan(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
Solution 2:
You may Use SpannableStringBuilder because it implements from spannable and CharSequence, also you may do anything with following
TextViewtxtTest= (TextView) findViewById(R.id.txt);
Stringtext="This is an example";
finalSpannableStringBuilderstr=newSpannableStringBuilder(text);
str.setSpan(newTypefaceSpan("monospace"), 0, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(newTypefaceSpan("serif"), 9, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(newForegroundColorSpan(getResources().getColor(R.color.white)), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(newForegroundColorSpan(getResources().getColor(R.color.grey)), 6, 8, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
str.setSpan(newandroid.text.style.StyleSpan(android.graphics.Typeface.BOLD), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txtTest.setText(str);
I have add colors.xml in values
<colorname="black">#000000</color><colorname="grey">#DCDCDC</color><colorname="white">#FFFFFF</color>
Post a Comment for "Making Part Of A String Bold In Textview"