【问题标题】:How to append/insert to TextView with retained format如何使用保留格式附加/插入到 TextView
【发布时间】:2016-03-17 09:43:53
【问题描述】:

我有这样的代码:

strings.xml

<string name="message1">Your money: <b>1000</b> <b>2000</b></string>
<string name="message2">Your money: <b>%1$s</b> <b>%2$s</b></string>

我想在 TextView 中显示它

MainActivity.java

// This one will render 1000 and 2000 in bold correctly
TextView mText1 = (TextView) findViewById(R.id.message1);
mText1.setText(getText(R.string.message1));

// This one fail to render 1000 and 2000 in bold    
int val1 = 1000, val2 = 2000;
TextView mText2 = (TextView) findViewById(R.id.message2);
mText1.setText(String.format(getText(R.string.message2).toString(), val1, val2));

我想让我可以通过将 String.format 应用于 android 字符串资源来格式化粗体/斜体文本。

【问题讨论】:

标签: java android string formatting textview


【解决方案1】:

你需要看看android string resource guide使用 HTML 标记进行样式化部分展示了如何做到这一点。

首先你需要给你的字符串资源如下(html转义开始的html标签)

<string name="message2">Your money: &lt;b>%1$s&lt;/b> &lt;b>%2$s&lt;/b></string>

然后按如下方式检索和格式化您的字符串

String text = getString(R.string.message2, val1, val2);
CharSequence styledText = Html.fromHtml(text);
mText2.setText(styledText);

【讨论】:

  • 像魅力一样工作。谢谢。
【解决方案2】:

你可以试试Html.fromHtml方法

int val1 = 1000, val2 = 2000;
mText2.setText(Html.fromHtml("Your money:" +"<b>"+val1+"</b>:"+"<b>"+val2+"</b>:"));

希望能提供帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-22
    • 1970-01-01
    • 2017-06-01
    • 2013-07-03
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多