我不知道如何使TextView上的特定文本变成粗体。
是这样的
txtResult.setText(id+" "+name);
我希望输出是这样的:
1111年尼尔
id和名称是我从数据库中检索值的变量,我想将id改为粗体,但只有id,所以名称不会受到影响,我不知道如何做到这一点。
我不知道如何使TextView上的特定文本变成粗体。
是这样的
txtResult.setText(id+" "+name);
我希望输出是这样的:
1111年尼尔
id和名称是我从数据库中检索值的变量,我想将id改为粗体,但只有id,所以名称不会受到影响,我不知道如何做到这一点。
当前回答
我用这个代码来加粗特定的单词…
Spanned string = Html.fromHtml("Normal string <b>BOLD STRING</b>");
textView.setText(string);
其他回答
如果你正在使用Kotlin和string资源,一个简单的解决方案是:
在strings.xml上创建你的字符串,使用<b> </b>加粗你想要的部分
<string name="my_message"> This is a very <b>important</b> message! </string>
在Kotlin代码中,你必须这样做
textView.setText(R.string.my_message)
就是这样!
重要提示!
使用属性语法将不起作用:
textView.text = resources.getString(R.string.my_message)
希望能有所帮助!
正如wtsang02所说,使用HTML是一种昂贵的开销。只使用本地解决方案。如果不需要修改字符串,只需使用SpannableString,而不是SpannableStringBuilder。
String boldText = "id";
String normalText = "name";
SpannableString str = new SpannableString(boldText + normalText);
str.setSpan(new StyleSpan(Typeface.BOLD), 0, boldText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(str);
只需在标签中添加这个
dangerouslySetInnerHTML={{__html: "<p>Your html text here.<p>"}}
根据@mladj0ni的回答,我得到了下面的代码。问题是如果你使用String。格式,它剥离了HTML标记,所以你必须转义strings.xml中的括号符号:
strings.xml:
<string name="welcome_messages">Hello, %1$s!你有<b>%2$d新消息</b>.</string> .</string> .
code.java:
String unspanned = String.format(Locale.US, "%s%s", getResources().getString(R.string. welcome_messages), 99);
Spanned spanned;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
spanned = Html.fromHtml(unspanned, Html.FROM_HTML_MODE_LEGACY);
} else {
spanned = Html.fromHtml(unspanned);
}
textView.setText(spanned);
它比SpannableStringBuilder简单。至于性能,如果只显示一个字符串,那么用户不会注意到解析它所花费的额外毫秒。
请在这里查看文档。
以防有人使用数据绑定。我们可以像这样定义绑定适配器
@BindingAdapter("html")
fun setHtml(view: TextView, html: String) {
view.setText(HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY))
}
然后我们可以在TextView上使用它
app:html="@{@string/bold_text}"
bold_text在哪里
<string name="bold_text"><![CDATA[Part of text is <b>bold</b>]]></string>