Android - Highlight a Word In a TextView?

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

    Try this library Android TextHighlighter.

    Implementations

    TextView.setText() gets a parameter as Spannable not only CharacterSequence. SpannableString has a method setSpan() which allows applying styles.

    See list of direct subclass form CharacterStyle https://developer.android.com/reference/android/text/style/CharacterStyle.html

    • example of giving background color and foreground color for word "Hello" in "Hello, World"
    Spannable spannable = new SpannableString("Hello, World");
    // setting red foreground color
    ForegroundSpan fgSpan = new ForegroundColorSpan(Color.red);
    // setting blue background color
    BackgroundSpan bgSpan = new BackgroundColorSPan(Color.blue);
    
    // setSpan requires start and end index
    // in our case, it's 0 and 5
    // You can directly set fgSpan or bgSpan, however,
    // to reuse defined CharacterStyle, use CharacterStyle.wrap()
    spannable.setSpan(CharacterStyle.wrap(fgSpan), 0, 5, 0);
    spannable.setSpan(CharacterStyle.wrap(bgSpan), 0, 5, 0);
    
    // apply spannableString on textview
    textView.setText(spannable);
    

提交回复
热议问题