0
我知道如何在iOS中完成此操作,但尚未在android中完成。如何构建Android的一个属性串,其中一部分是大胆地在如何为api level 11构造android AttributedString
“这是一个大胆部分的例子”
我知道如何在iOS中完成此操作,但尚未在android中完成。如何构建Android的一个属性串,其中一部分是大胆地在如何为api level 11构造android AttributedString
“这是一个大胆部分的例子”
FWIW,我从来没有见过使用AttributedString
,在〜6.5岁Android开发工作。
实施Spanned
的类包含标记规则(“跨度”)。动态构造一个最简单的方法是使用Html.fromHtml()
解析带有基本标记(如<b>
)的HTML字符串。字符串资源(例如,res/values/strings.xml
)也支持<b>
,<i>
和<u>
标签。
或者,您可以自己申请跨度。在下面的示例代码中,我得到的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);
}
为粗体或斜体,你会使用StyleSpan
而不是BackgroundColorSpan
,等等。