在Android中如何更改在List中搜索的特定字母/字符的颜色

swd*_*per 8 search android textview android-listview

我有一个包含某些项目的ListView,我已经EditText在列表上方放置了Search向用户提供设施,意味着,通过在内部键入EditText并单击任何按钮等,用户可以搜索列表中是否存在某个项目.

现在我想要的是:如果用户输入的字母/字符存在于任何列表项中,则以those letters only红色或蓝色或任何其他颜色更改.例如,我有一个水果列表,我正在搜索Apple,所以当我开始输入app ... le时,那么只有用户输入的那些字符app(在这种情况下)的颜色应该更改为RED ,如果项目Apple在列表中,则为蓝色或任何其他颜色.

任何人都可以告诉我这是否可以在Android中做,如果是,那么如何做到这一点.提前致谢

phe*_*atd 3

更简单的方法是注册一个 TextChangedListener:

 editText.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        //retrieve the typed text lecter ad char array something like typedChar[]
        //Here parsing the List and modify the lecter
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
});
Run Code Online (Sandbox Code Playgroud)

然后我们必须重新加载ListView,可以在适配器上使用notifyDataSetChanged()(必须更改某些内容才能触发事件)

myListViewAdapter.notifyDataSetChanged()
Run Code Online (Sandbox Code Playgroud)

最后在适配器中:

public class CustomAdapterOptimize extends ArrayAdapter<Contatto> {

      public CustomAdapterOptimize(Context context, int textViewResourceId,
             List<Contatto> objects) {
           super(context, textViewResourceId, objects);
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
           TextView tx = (TextView)convertView;
           SpannableString text = getItem(position);
           for(char:typedChar)
           if(tx.getText().contains(char)){
                // make "text" (characters pos-1 to pos) red  
                text.setSpan(new ForegroundColorSpan(Color.RED), tx.getText().indexOf(char) - 1, tx.getText().indexOf(char), 0);  
                textView.setText(text, BufferType.SPANNABLE);
           }
      }
 }
Run Code Online (Sandbox Code Playgroud)

请注意,必须针对性能和逻辑调整此代码,但这可能是一个很好的启动。