我知道如何在 iOS 中执行此操作,但还不知道 android .如何在 android 中构造一个属性字符串,其中一部分是粗体,如
“这是带有粗体部分的示例”
最佳答案
FWIW,我从未见过AttributedString
在大约 6.5 年的 Android 开发工作中使用过。
类实现 Spanned
包含标记规则(“跨度”)。动态构造一个的最简单方法是使用 Html.fromHtml()
解析带有 <b>
等基本标签的 HTML 字符串.字符串资源(例如 res/values/strings.xml
)也支持 <b>
, <i>
, 和 <u>
标签。
或者,您可以自己应用 span。在下面的示例代码中,我得到了 CharSequence
来自TextView
,删除所有现有跨度,并使用 BackgroundColorSpan
突出显示搜索词:
private void searchFor(String text) {
TextView prose=(TextView)findViewById(R.id.prose);
Spannable raw=new SpannableString(prose.getText());
BackgroundColorSpan[] spans=raw.getSpans(0,
raw.length(),
BackgroundColorSpan.class);
for (BackgroundColorSpan span : spans) {
raw.removeSpan(span);
}
int index=TextUtils.indexOf(raw, text);
while (index >= 0) {
raw.setSpan(new BackgroundColorSpan(0xFF8B008B), index, index
+ text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
index=TextUtils.indexOf(raw, text, index + text.length());
}
prose.setText(raw);
}
(来自 this sample project)
对于粗体或斜体,您可以使用 StyleSpan
而不是 BackgroundColorSpan
, 等等。
关于android - 如何为 api 级别 11 构建 android AttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26197395/