[英]How to construct android AttributedString for api level 11
FWIW,我從未見過使用AttributedString
,在~6。5年的Android開發工作中。
實現Spanned
的類包含標記規則(“spans”)。 動態構造一個的最簡單方法是使用Html.fromHtml()
來解析帶有<b>
等基本標簽的HTML字符串。 字符串資源(例如, res/values/strings.xml
)也支持<b>
, <i>
和<u>
標記。
或者,您可以自己應用跨度。 在下面的示例代碼中,我從TextView
獲取CharSequence
,刪除所有現有的跨度,並使用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
,依此類推。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.