Make text content in bold and plain text

I am using textview to store a string coming from a web service. The string comes with this format. "sample text {{b}} bold text {{/ b}}, etc.". I need to display bold text in my text view. in one operation, I can just pass the string. Do I have the ability to use a string with colors, font, etc.?

Note. I have no problem parsing the text. I just want to find a way to pass my parsed text to a textview.

thanks

+4
source share
3 answers

I solved this problem using SpannableString, for those who need code, I can change this class as I see fit

public class RichTextHelper { public static SpannableStringBuilder getRichText(String text){ SpannableStringBuilder builder=new SpannableStringBuilder(); String myText=text; boolean done=false; while(!done){ if((myText.indexOf("{{b}}")>=0) && (myText.indexOf("{{b}}")<myText.indexOf("{{/b}}"))){ int nIndex=myText.indexOf("{{b}}"); String normalText=myText.substring(0,nIndex); builder.append(normalText); myText=myText.substring(nIndex+5); }else if((myText.indexOf("{{/b}}")>=0)){ int bIndex=myText.indexOf("{{/b}}"); String boldText=myText.substring(0,bIndex); builder.append(boldText); myText=myText.substring(bIndex+6); int start=builder.length()-bIndex-1; int end =builder.length();//-1; if((start>=0) && (end>start)){ builder.setSpan(new StyleSpan(Typeface.BOLD), start, end, 0); } }else{ if(myText.contains("{{/b}}")) myText=myText.replace("{{/b}}", ""); builder.append(myText); done=true; } } return builder; } 

}

+2
source

When you install text in text form, use:

 mytextview.setText(Html.fromHtml(sourceString)); 

then you will get the text in real format.

+14
source

I thought that the selected answer did not give a satisfactory result. I wrote my own function, which takes 2 lines; Full text and part of the text you want to make bold.

It returns a SpannableStringBuilder with the text textToBold from the text in bold.

I find it possible to make a substring in bold without using it in tags.

 /** * Makes a substring of a string bold. * @param text Full text * @param textToBold Text you want to make bold * @return String with bold substring */ public static SpannableStringBuilder makeSectionOfTextBold(String text, String textToBold){ SpannableStringBuilder builder=new SpannableStringBuilder(); if(textToBold.length() > 0 && !textToBold.trim().equals("")){ //for counting start/end indexes String testText = text.toLowerCase(Locale.US); String testTextToBold = textToBold.toLowerCase(Locale.US); int startingIndex = testText.indexOf(testTextToBold); int endingIndex = startingIndex + testTextToBold.length(); //for counting start/end indexes if(startingIndex < 0 || endingIndex <0){ return builder.append(text); } else if(startingIndex >= 0 && endingIndex >=0){ builder.append(text); builder.setSpan(new StyleSpan(Typeface.BOLD), startingIndex, endingIndex, 0); } }else{ return builder.append(text); } return builder; 

}

0
source

All Articles