我使用 BackgroundColorSpan 来显示 TextView 的多个突出显示。它在 Android API 23 及更低版本上正确显示,但在 API 24 和 25 上存在问题。
final static String article1 = "Last year’s Google Pixel and Pixel XL were without question " +
"two of the hottest new smartphones of 2016. Google surprised fans by ditching its " +
"Nexus lineup of devices and moving from affordable upper mid-range devices to " +
"high-end flagship phones. Sure they were more expensive than Google phones had " +
"been in the past, but they were also a much better platform for showcasing the best " +
"of what Android has to offer, featuring high-end specs and a sleek metal and " +
"glass design.";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SpannableStringBuilder sb = new SpannableStringBuilder(article1);
BackgroundColorSpan span;
for (int i = 0; i < 3; i++) {
span = new BackgroundColorSpan(Color.YELLOW);
sb.setSpan(span, 23, 214, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
span = new BackgroundColorSpan(Color.RED);
sb.setSpan(span, 67, 83, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
span = new BackgroundColorSpan(Color.RED);
sb.setSpan(span, 216, 236, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
TextView tv = (TextView) findViewById(R.id.body);
tv.setText(sb);
}
}
如果循环 3,则仅显示一个红色突出显示。 如果循环 2,将显示两个红色突出显示。
这似乎与 API 24+ 中的一些更改有关
- https://issuetracker.google.com/issues/37085040
- https://issuetracker.google.com/issues/37135960