我不知道如何使TextView上的特定文本变成粗体。
是这样的
txtResult.setText(id+" "+name);
我希望输出是这样的:
1111年尼尔
id和名称是我从数据库中检索值的变量,我想将id改为粗体,但只有id,所以名称不会受到影响,我不知道如何做到这一点。
我不知道如何使TextView上的特定文本变成粗体。
是这样的
txtResult.setText(id+" "+name);
我希望输出是这样的:
1111年尼尔
id和名称是我从数据库中检索值的变量,我想将id改为粗体,但只有id,所以名称不会受到影响,我不知道如何做到这一点。
当前回答
只需要在HTML中构建字符串并设置它:
String sourceString = "<b>" + id + "</b> " + name;
mytextview.setText(Html.fromHtml(sourceString));
其他回答
我用这个代码来加粗特定的单词…
Spanned string = Html.fromHtml("Normal string <b>BOLD STRING</b>");
textView.setText(string);
正如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);
只需要在HTML中构建字符串并设置它:
String sourceString = "<b>" + id + "</b> " + name;
mytextview.setText(Html.fromHtml(sourceString));
如果你正在使用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)
希望能有所帮助!
我来这里是为了提供一个最新的解决方案,因为我对现有的答案不满意。 我需要一些可以用于翻译文本的东西,并且没有使用Html.fromHtml()的性能影响。 如果您正在使用Kotlin,这里有一个扩展函数,可以轻松地将文本的多个部分设置为粗体。这就像Markdown一样工作,如果需要,可以扩展到支持其他Markdown标签。
val yourString = "**This** is your **string**.".makePartialTextsBold()
val anotherString = getString(R.string.something).makePartialTextsBold()
/**
* This function requires that the parts of the string that need
* to be bolded are wrapped in ** and ** tags
*/
fun String.makePartialTextsBold(): SpannableStringBuilder {
var copy = this
return SpannableStringBuilder().apply {
var setSpan = true
var next: String
do {
setSpan = !setSpan
next = if (length == 0) copy.substringBefore("**", "") else copy.substringBefore("**")
val start = length
append(next)
if (setSpan) {
setSpan(StyleSpan(Typeface.BOLD), start, length,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
}
copy = copy.removePrefix(next).removePrefix("**")
} while (copy.isNotEmpty())
}
}