How to change background color of searched text in listview-cursoradapter while typing in searchview?

…衆ロ難τιáo~ 提交于 2019-12-06 01:57:23

Apologize for answering after a while, but still it would help someone in need.

What i end up doing is pass the text to a method in adapter, then find the text in bindView() with Pattern-Matcher and highlight the text with SpannableString

Following is the code in adapter:

public class AdapterSingleChat extends CursorAdapter {

    private static int indexThumb;

    //String to search and highlight
    String textToSearch = null;

    public AdapterSingleChat(Context context, Cursor cursor, int flags) {
        super(context, cursor, flags);

        //caching the column index
        indexThumb = cursor.getColumnIndex(SQLiteStoreDB.ROW_TEXT);
   }

   //ViewHolder()...

   //newView()....

   @Override
   public void bindView(View view, Context context, Cursor cursor){

        //Text from cursor in which search will perform
        String cursorText = cursor.getString(indexText);

        //Spannable string to highlight matching searched words
        SpannableString spannableStringSearch = null;

        if ((textToSearch != null) && (!textToSearch.isEmpty())) {


            spannableStringSearch = new SpannableString(cursorText);

            //compile the pattern of input text
            Pattern pattern = Pattern.compile(textToSearch,
                    Pattern.CASE_INSENSITIVE);

            //giving the compliled pattern to matcher to find matching pattern in cursor text
            Matcher matcher = pattern.matcher(cursorText);
            spannableStringSearch.setSpan(new BackgroundColorSpan(
                        Color.TRANSPARENT), 0, spannableStringSearch.length(),
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            while (matcher.find()) {

                //highlight all matching words in cursor with white background(since i have a colorfull background image)
                spannableStringSearch.setSpan(new BackgroundColorSpan(
                            Color.WHITE), matcher.start(), matcher.end(),
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        if(spannableStringSearch != null{

            //if search has performed set spannable string in textview
            holder.tvCursorText.setText(spannableStringSearch);
        }else{

            //else set plain cursor text
            holder.tvCursorText.setText(cursorText);
        }
   }

   //Pass the text from activity(from  SearchManager, EditText or any other input type) here
   private void searchText(String text) {

       this.textToSearch = text;
   }

and yes, do not forget to swapCursor() or notifyDataSetChanged() after inputting words.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!