Make textview's content with both bold and regular text
Question
I'm using a textview to hold a string coming from a web service. String comes with a format like this. "sample text {{b}}bold text{{/b}} and so on". I need to show the bold text bold in my textview. in a single operation I just can pass the string. Do I have a chance to use a string with color, font, etc properties?
Note: I don t have problems with parsing the text I just want to find a way to pass my parsed text to textview.
Thanks
Solution 2
I solved this problem by using SpannableString, for who who needs code, can change this class as they wish
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;
}
}
OTHER TIPS
When you set the text in your text view then use:
mytextview.setText(Html.fromHtml(sourceString));
then you will get the text in actual format.
I thought that the chosen answer didn't provide a satisfactory result. I have written my own function which takes 2 strings; The full text and the part of the text you want to make bold.
It returns a SpannableStringBuilder with the 'textToBold' from 'text' bolded.
I find the ability to make a substring bold without wrapping it in tags useful.
/**
* 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;
}