Android - Highlight a Word In a TextView?

后端 未结 9 1772
予麋鹿
予麋鹿 2020-12-07 15:57

I have a database search query which search in the database for a word entered by the user and return a Cursor.

In my ListActivity

9条回答
  •  不思量自难忘°
    2020-12-07 16:26

    Based on the previous answers I developed the following function, you can copy/paste it

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

提交回复
热议问题