【问题标题】:Android EditText highlight multiple wordsAndroid EditText 突出显示多个单词
【发布时间】:2015-01-10 02:32:16
【问题描述】:

这是我当前的代码:

    public void markWords(String str) {
        str = str.replace("\n", " <br>");
        int spamLength = 20;
        String colorSpam = "#ED9E15";
        String colorBad = "red";
        int i = 0;

        for(String word : str.split(" ")) {
            if(word.length() > spamLength) {
                str = str.replace(word, "<font color='"+colorSpam+"'>"+word+"</font>");
                i++;
            }
        }

        for(String bad : blacklist) {
            if (!bad.startsWith("#") && str.toLowerCase().contains(bad.toLowerCase())) {
                for (String word : str.split(" ")) {
                    if (word.toLowerCase().contains(bad.toLowerCase())) {
                        String rightWord = getRightCased(word, bad);
                        if (word.length() > spamLength) {
                            str = str.replace(rightWord, "</font><font color='"+colorBad+"'>" + rightWord + "</font><font color='"+colorSpam+"'>");
                        } else {
                            str = str.replace(rightWord, "<font color='"+colorBad+"'>" + rightWord + "</font><font color='black'></font>");
                        }
                        i++;
                    }
                }
            }
        }

        text.setText(Html.fromHtml(str), TextView.BufferType.SPANNABLE);
        String gefunden = "Es wurden " + i + " Wörter gefunden.";
        if(i == 1) {
            gefunden = "Es wurde " + i + " Wort gefunden.";
        }
            Toast msg = Toast.makeText(getApplicationContext(), gefunden, Toast.LENGTH_SHORT);
            msg.show();
    }

    public String getRightCased(String str, String bad) {
        String string = str;

        for(int i = 1; i < str.length(); i++) {
            if(!string.toLowerCase().startsWith(bad.toLowerCase())) {
                string = string.substring(1);
            }
        }
        for(int i = 1; i < str.length(); i++) {
            if(!string.toLowerCase().endsWith(bad.toLowerCase())) {
                string = string.substring(0, string.length() - 1);
            }
        }
        return string;
    }

它第一次工作,但是当文本包含 html 标签或一些空格被添加到文本中然后再次突出显示单词时崩溃......如何在不使用 html 标签的情况下突出显示多个单词?

【问题讨论】:

    标签: android android-edittext word highlight


    【解决方案1】:

    真正让文本在 TextView(或 EditText)中显示样式的方法是创建 Span,例如 ColorSpannable。这就是 HTML.fromHtml() 为您所做的。使用 HTML 是最简单的方法,但正如您很快指出的那样,如果您尝试在 html 文本上执行此操作或重复执行此操作,则会出现问题。如果您手动创建自己的 span 会很痛苦,但您可以通过从不使用 HTML 来避免这些问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-05
      • 2017-08-30
      • 2012-01-29
      • 2015-11-13
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 2012-06-03
      相关资源
      最近更新 更多