I know how to do this in iOS but not yet in android. How do I construct an attributed string in android where a portion is bold as in
"this is the example with a bold portion"
I know how to do this in iOS but not yet in android. How do I construct an attributed string in android where a portion is bold as in
"this is the example with a bold portion"
FWIW, I have never seen AttributedString
used, in ~6.5 years of Android development work.
A class implementing Spanned
contains markup rules ("spans"). The simplest way to construct one dynamically is by using Html.fromHtml()
to parse an HTML string with basic tags like <b>
. String resources (e.g., res/values/strings.xml
) also support <b>
, <i>
, and <u>
tags.
Or, you can apply spans yourself. In the sample code that follows, I get the CharSequence
from a TextView
, remove all existing spans, and highlight search terms with a 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);
}
(from this sample project)
For boldface or italics, you would use StyleSpan
instead of BackgroundColorSpan
, and so forth.