如何在EditText Android中取消粗体和取消突出显示所选文本

时间:2018-11-04 09:45:52

标签: java android

嗨,我能够加粗或突出显示选定的文本,但是当尝试在该加粗或突出显示的文本中取消突出显示或取消突出显示时,则会取消突出显示或取消突出显示整个文本。请告诉我我的代码在做什么错。这是我的代码

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 (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);
    }

0 个答案:

没有答案