Search code examples
androidtextviewbold

Make textview's content with both bold and regular text


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

  • 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;
    }
    

    }