【问题标题】:How to check for if else condition for highlighted text?如何检查突出显示文本的 if else 条件?
【发布时间】:2019-04-06 06:53:39
【问题描述】:

我想实现IfElse 条件来检查所选文本是否突出显示。我可以突出显示文本,但不知道要再次删除突出显示文本的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);
    }
}

【问题讨论】:

    标签: javascript java android eclipse


    【解决方案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);
        }
    

    【讨论】:

    • 感谢您的回答。这对我有用,但唯一的问题是,当我突出显示整行然后取消突出显示突出显示的行文本的一部分时,它会取消突出显示整个文本行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多