2013-02-10 82 views
3

我有這個字符串:String數組文本格式

String[] text = {"Address 1: Street nr.45 ", 
     "Address 2: Street nr.67", 
     "Address 3: Street nr. 56 \n Phone number: 000000000"}; 

它得到通過以後使用:從微調選擇項目時

 ((TextView)findViewById(R.id.adresa)).setText(text[newSelectedAddress]); 

如何添加格式到字符串中的文本?我想要地址與大膽,街道號碼。與斜體

回答

3

你必須使用Spannable s。雖然創造它們有點羅嗦,看起來很複雜,但它不是火箭科學。 一個例子:

String source = "This is example text"; 
SpannedString out = new SpannedString(source); 
StyleSpan boldSpan = new StyleSpan(Typeface.BOLD); 
StyleSpan boldSpan2 = new StyleSpan(Typeface.BOLD); 
out.setSpan(boldSpan, 1, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
out.setSpan(boldSpan2, 9, 12, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

結果:T s是ËXAM PLE文本

然後你setText這個Spannable,而不是正常的字符串。

+0

好一點是,該字符串文本我將有30個文本。如果我這樣做,它會取而代之。 – 2013-02-10 13:04:29

+0

@CatalinH只需創建一個方法,該方法將文本格式化,格式化參數(粗體等)以及要格式化的文本的起始索引和長度。在需要的地方調用該方法。絕對不需要重複30次。 – Simon 2013-02-10 13:30:10

+0

我得到的錯誤:類型不匹配:無法從SpannedString轉換爲Spannable – 2013-02-10 14:16:50

1

得很不喜歡這個仁兄:

String[] text = {"Address 1: Street nr.45 ", 
      "Address 2: Street nr.67", 
      "Address 3: Street nr. 56 \n Phone number: 000000000"}; 
    String tempString = text[newSelectedAddress]; 
    CharSequence charSeq= new SpannedString(tempString); 
    Spannable spannable = (Spannable) charSeq; 
    StyleSpan boldSpan = new StyleSpan(Typeface.BOLD); 
    StyleSpan boldSpan2 = new StyleSpan(Typeface.ITALIC); 
    spannable.setSpan(boldSpan, 0, "Address".length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    spannable.setSpan(boldSpan2, tempString.indexOf("Street"), tempString.indexOf("Street")-1 +"Street".length()-1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
    ((TextView)findViewById(R.id.adresa)).setText(spannable); 

感謝

+0

02-10 16:09:06.800:E/AndroidRuntime(612):java.lang.ClassCastException:android.text.SpannedString無法轉換爲android.text.Spannable – 2013-02-10 14:14:48

0

有一個黑客位的允許串識別的HTML粗體和斜體格式。加入這樣的事情您的strings.xml:

<string name="address"><![CDATA[<b>Address %1$s</b>: <i>Street nr. %2$s </i>]]></string> 

然後:

Resources res = getResources(); 
formattedString = res.getString(R.string.address, "1", "45"); 
// equivalent to String.format(res.getString(R.string.address), "1", "45") 
Spannable s = Html.from Html(formattedString); 
textView.setText(s);