首页 > 解决方案 > 如何在edittext 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);
    }

标签: javaandroid

解决方案


推荐阅读