Android - Highlight a Word In a TextView?

后端 未结 9 1777
予麋鹿
予麋鹿 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:39

    More Easy Way

    You can use Spannable class for highlighting/formatting part of Text.

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

    Here is the method.

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

    You can check this answer for clickable highlighted text.

提交回复
热议问题