簡體   English   中英

當輸入文本與光標字符串匹配時,如何更改listview-cursoradapter中的textview背景顏色?

[英]How to change textview background color in listview-cursoradapter when input text matches with cursor string?

我正在嘗試在listview中實現搜索功能,例如在瀏覽器中進行文本搜索。

我已經成功地在光標數據中搜索輸入的單詞。 但是找到匹配項后,如何更改相應單詞的背景顏色?

這是bindview中的搜索代碼

if (searchEnabled) {

    cursor.moveToFirst();

    while (cursor.moveToNext()) {

        String cursorText = cursor.getString(indexMessage);
        if (s.equals(searchText.toString())) {

            //Change matched word's(textview) background color here
            holder.textMessage.setBackgroundColor(Color.WHITE);
            Log.i("Cursor Scan:", cursorText);
        }
    }
}

調用notifyDataSetChanged() ,它僅更改最后一行的notifyDataSetChanged()顏色。

我嘗試通過從getChildAt()獲取listview文本來進行搜索,但部分成功,但是該視圖不一致,並且在滾動時變成了它的原始狀態(因為此listview從游標中膨脹了)。

我嘗試使用以下代碼在listview文本中進行搜索:

private void updateListView(String textForSearch) {

    LocalStoreDB localDB = new LocalStoreDB(getApplicationContext());
    localMessageDB.openDB();
    Cursor cursorForSearch = localDB.selectMessageDB();
    cursorForSearch.moveToFirst();

    while (cursorForSearch.moveToNext()) {

        int position = cursorForSearch.getPosition();

        View v = listview.getChildAt(position);

        TextView tv = (TextView) v.findViewById(R.id.textMessage);

        SpannableString cursorString = new SpannableString(tv.getText());
        Pattern p = Pattern.compile(textForSearch);
        Matcher m = p.matcher(cursorString);
        while (m.find()) {

            cursorString.setSpan(new BackgroundColorSpan(Color.WHITE),
                    m.start(), m.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            Log.i("m.find()", cursorString.toString());
        }
        tv.setText(cursorString);
    }

    localDB.closeDB();
}

您可以像這樣設置textview的背景顏色

yourTextView.setBackgroundColor("0xff0000ff");

我看不到其余的代碼,但也許您必須在設置顏色后通知您所做的更改。

希望能幫助到你

在您的情況下,我會嘗試這樣的事情:

TextView tv;    
for(int i=0;i<listview.get.getCount();i++){

   tv =(TextView) listview.getChildAt(i).findViewById(R.id.textMessage);
   if(tv.getText().equalsIgnoreCase(searchstring)){

       tv.setBackgroundColor("0xff0000ff");
   } 
   else{
       tv.setBackgroundColor("0xffffffff");
   }
}

 listViewAdapter.notifyDataSetChanged();

抱歉,我遲到了。

我在另一個線程中回答了這個問題。 請點擊此鏈接: https : //stackoverflow.com/a/34287029/4688535

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM