我想实现If
和Else
条件,以检查所选文本是否突出显示。我可以突出显示文本,但是不知道突出显示的文本要再次删除的if()
条件。我搜索了很多,但没有得到明确的答案。这是我的代码:
private void highlightTextCondition() {
int selectionStart = bodyText.getSelectionStart();
int selectionEnd = bodyText.getSelectionEnd();
if (selectionStart > selectionEnd) {
int temp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = temp;
}
if (selectionEnd > selectionStart) {
Spannable str = bodyText.getText();
boolean exists = false;
for (int i = 0; i < str.length(); i++) {
if (**want this statement here for highlight texted**) {
str.removeSpan(*****);
exists = false;
}
}
if (!exists) {
str.setSpan(new BackgroundColorSpan(Color.YELLOW), selectionStart, selectionEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
exists = true;
}
bodyText.setSelection(selectionStart, selectionEnd);
}
}
答案 0 :(得分:1)
尝试一下,但是我不确定如何仅删除选定的文本突出显示颜色
if (selectionEnd > selectionStart) {
Spannable str = bodyText.getText();
boolean exists = false;
for (CharacterStyle span : str.getSpans(selectionStart, selectionEnd, CharacterStyle.class)) {
if (span instanceof BackgroundColorSpan)
str.removeSpan(span);
exists = true;
}
if (!exists) {
str.setSpan(new BackgroundColorSpan(Color.YELLOW), selectionStart, selectionEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
bodyText.setSelection(selectionStart, selectionEnd);
}