2011-05-18 42 views
4

我使用textview來保存來自Web服務的字符串。字符串帶有這樣的格式。 「示例文本{{b}}粗體文本{{/ b}}等等」。我需要在我的文本視圖中顯示粗體文本。在一次操作中,我只能傳遞字符串。我有機會使用帶有顏色,字體等屬性的字符串嗎?用粗體和普通文本製作textview的內容

注:我沒有解析文本的問題,我只是想找到一種方法將我的解析文本傳遞給textview。

感謝

+2

這是http://stackoverflow.com/questions/1529068/android-is-it-possible-to-have-multiple-styles-inside-a-textview – CharlieMezak 2011-05-18 14:06:09

回答

2

我用SpannableString,對於誰需要誰的代碼解決了這個問題,可以改變這一類,因爲他們希望

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

}

+0

的欺騙似乎它有一個錯誤。首先{{b}}被忽略。你必須有int start = builder.length() - bIndex/* - 1 * /; – 2013-05-13 14:19:48

14

當你設置在文本視圖中的文本,然後用:

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

那麼你會得到實際格式的文本。

0

我認爲選擇答案沒有提供令人滿意的結果。我寫了我自己的函數,它需要2個字符串;全文和你想要粗體的部分文字。

它返回一個SpannableStringBuilder,其中的'textToBold'從'text'加粗。

我發現能夠使一個子字符串粗體而不包含在有用的標籤中。

/** 
* 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; 

}