I need to create a String placed in a TextView that will display a string like this:
First Part Not Bold BOLD rest not bold
So I want to know how I could use SpannableStringBuilder
to do this?
I could use three TextEdit to accomplish this but I would like to use best solution.
Kotlin |Java. public class SpannableStringBuilder. extends Object implements CharSequence, GetChars, Spannable, Editable, Appendable. java.lang.Object.
↳ android.text.SpannableString. This is the class for text whose content is immutable but to which markup objects can be attached and detached. For mutable text, see SpannableStringBuilder .
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).
First Part Not Bold BOLD rest not bold
You can do this either as @Rajesh suggested or by this.
String normalBefore= "First Part Not Bold "; String normalBOLD= "BOLD "; String normalAfter= "rest not bold"; String finalString= normalBefore+normalBOLD+normalAfter; Spannable sb = new SpannableString( finalString ); sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), finalString.indexOf(normalBOLD)+ normalBOLD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); //bold sb.setSpan(new AbsoluteSizeSpan(intSize), finalString.indexOf(normalBOLD)+ normalBOLD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);//resize size
to show this in TextView
textview.setText(sb, TextView.BufferType.SPANNABLE);
The accepted answer is fine (and I upvoted it), but it fails to use the SpannableStringBuilder as the submitter requested. As I had a case where the Builder made the most sense, here is the code for that (with a bonus use of also changing the color of the text if that is helpful to others). Note that you could also provide the initial string to the SpannableStringBuilder constructor, but I set it here to use "append" to be clear that you can append a lot before your desired "bold" text and then just record the start as shown. I would suspect that this is also faster code than the accepted answer.
SpannableStringBuilder longDescription = new SpannableStringBuilder(); longDescription.append("First Part Not Bold "); int start = longDescription.length(); longDescription.append("BOLD"); longDescription.setSpan(new ForegroundColorSpan(0xFFCC5500), start, longDescription.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); longDescription.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), start, longDescription.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); longDescription.append(" rest not bold");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With