I set the following text and style in my EditText
:
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append("Hello");
sb.setSpan(new StyleSpan(Typeface.BOLD), 0, 5, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.append("World Test");
et.setText(sb);
The result is this: " Hello World Test". This is fine. Now when I position the cursor after the "d" character (ie before the space that separates World
and Test
) and enter a character, the Hello automatically loses its bold style.
Why is that? That is confusing me. It only happens when positioning the cursor directly after the "d" in World
and entering a character. For all other cursor positions it works as expected.
Why is that and how to fix it? I want Hello to stay in bold.
may be you should try this
SpannableStringBuilder sb = new SpannableStringBuilder();
int s = sb.length();
sb.append("Hello");
sb.setSpan(new ForegroundColorSpan(0xFFCC5500), s,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), s,
sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
sb.append("World Test");
et.setText(sb);
or try this after api 21
SpannableStringBuilder sb = new SpannableStringBuilder();
StyleSpan bold = new StyleSpan(android.graphics.Typeface.BOLD);
sb.append("Hello")
.append("BOLD ", bold, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
.append("World");
like html style try below
String str = "<b>" + "hello" + "</b> " + "World Test";
et.setText(Html.fromHtml(str));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.