Android - 突出显示TextView中的单词?

iTu*_*rki 27 android highlighting textview android-listview

database search query在数据库中搜索用户输入的单词并返回a Cursor.

在我ListActivity,我有一个ListView将持有项目(光标项目).该ListView项目的布局基本上是一个TextView.我的意思是,这ListView将是一个列表TextView.

我想要的是突出search term它出现在哪里TextView.我的意思是突出显示:不同的颜色或不同的背景颜色或任何东西使它与文本的其余部分不同.

这可能吗?如何?

更新:

cursor = myDbHelper.search(term);  //term: a word entered by the user.
cursor.moveToFirst();
String[] columns = {cursor.getColumnName(1)}; 
int[] columnsLayouts = {R.id.item_title}; //item_title: the TextView holding the one raw
ca = new SimpleCursorAdapter(this.getBaseContext(), R.layout.items_layout, cursor,columns , columnsLayouts);
lv = getListView();
lv.setAdapter(ca);
Run Code Online (Sandbox Code Playgroud)

对于@Shailendra:该search()方法将返回一些标题.我想突出那些与这个term词匹配的标题中的单词.我希望现在很清楚.

Sha*_*wat 38

在word周围插入颜色的HTML代码并将其设置为textView.

喜欢

String newString = oldString.replaceAll(textToHighlight, "<font color='red'>"+textToHighlight+"</font>");
textView.setText(Html.fromHtml(newString));
Run Code Online (Sandbox Code Playgroud)


小智 21

TextView textView = (TextView)findViewById(R.id.mytextview01);

//use a loop to change text color
Spannable WordtoSpan = new SpannableString("partial colored text");        
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 2, 4, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(WordtoSpan);
Run Code Online (Sandbox Code Playgroud)

数字2和4是文本着色的开始/停止索引,在这个例子中,"rti"将被着色.

所以你基本上只需在标题中找到搜索词的起始索引:

int startIndex = titleText.indexOf(term);
int stopIndex = startIndex + term.length();
Run Code Online (Sandbox Code Playgroud)

然后用索引替换数字2和4,用标题字符串替换"部分彩色文本".

来源:https://stackoverflow.com/a/10279703/2160827


Khe*_*raj 7

更简单的方法

您可以使用Spannable类突出显示/格式化文本的一部分。

textView.setText("Hello, I am Awesome, Most Awesome"); // set text first
setHighLightedText(textView, "a"); // highlight all `a` in TextView
Run Code Online (Sandbox Code Playgroud)

输出

这是方法。

 /**
     * use this method to highlight a text in TextView
     *
     * @param tv              TextView or Edittext or Button (or derived from TextView)
     * @param textToHighlight Text to highlight
     */
    public void setHighLightedText(TextView tv, String textToHighlight) {
        String tvt = tv.getText().toString();
        int ofe = tvt.indexOf(textToHighlight, 0);
        Spannable wordToSpan = new SpannableString(tv.getText());
        for (int ofs = 0; ofs < tvt.length() && ofe != -1; ofs = ofe + 1) {
            ofe = tvt.indexOf(textToHighlight, ofs);
            if (ofe == -1)
                break;
            else {
                // set color here
                wordToSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + textToHighlight.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv.setText(wordToSpan, TextView.BufferType.SPANNABLE);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

您可以检查此答案以获取可点击的突出显示文本。


Sum*_*mit 5

我知道这是个老问题,但我创建了一种方法来突出显示 string\paragraph 中的重复单词。

private Spannable highlight(int color, Spannable original, String word) {
    String normalized = Normalizer.normalize(original, Normalizer.Form.NFD)
            .replaceAll("\\p{InCombiningDiacriticalMarks}+", "");

    int start = normalized.indexOf(word);
    if (start < 0) {
        return original;
    } else {
        Spannable highlighted = new SpannableString(original);
        while (start >= 0) {
            int spanStart = Math.min(start, original.length());
            int spanEnd = Math.min(start+word.length(), original.length());

            highlighted.setSpan(new ForegroundColorSpan(color), spanStart,
                    spanEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

            start = normalizedText.indexOf(word, spanEnd);
        }
        return highlighted;
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

textView.setText(highlight(primaryColor, textAll, wordToHighlight));
Run Code Online (Sandbox Code Playgroud)


Sza*_*cze 5

根据前面的回答我开发了以下功能,你可以复制/粘贴它

 private void highlightMask(TextView textView, String text, String mask) {
            boolean highlightenabled = true;
            boolean isHighlighted = false;

            if (highlightenabled) {
                if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(mask)) {
                    String textLC = text.toLowerCase();
                    mask = mask.toLowerCase();

                    if (textLC.contains(mask)) {
                        int ofe = textLC.indexOf(mask, 0);
                        Spannable wordToSpan = new SpannableString(text);
                        for (int ofs = 0; ofs < textLC.length() && ofe != -1; ofs = ofe + 1) {
                            ofe = textLC.indexOf(mask, ofs);
                            if (ofe == -1) {
                                break;
                            } else {
                                // set color here
                                wordToSpan.setSpan(new BackgroundColorSpan(0xFFFFFF00), ofe, ofe + mask.length(),
                                                   Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                                textView.setText(wordToSpan, TextView.BufferType.SPANNABLE);
                                isHighlighted = true;
                            }
                        }

                    }
                }
            }

            if (!isHighlighted) {
                textView.setText(text);
            }
        }
Run Code Online (Sandbox Code Playgroud)