3

我有这个字符串:

    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]);

从微调器中选择项目时。

如何为字符串内的文本添加格式?我希望地址带有粗体,街道编号。斜体

4

3 回答 3

3

你必须使用Spannables。虽然创建它们有点罗嗦而且看起来很复杂,但这不是火箭科学。一个例子:

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

结果:这是示例文本

然后你用setText这个 Spannable 而不是普通的 String。

于 2013-02-10T12:42:42.373 回答
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);

谢谢

于 2013-02-10T13:18:43.180 回答
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);
于 2013-07-18T22:02:09.127 回答