Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Android how to change the color of a particular letter/character which is being searched inside the List

I have a ListView containing certain items and I have placed a EditText above the list to provide the Search facility to the user, means, by typing inside the EditText and clicking any button etc., user can search whether certain item is present in the list or not.

Now what I want is that: if the letters / characters typed by the user are present inside any list item, then those letters only to be changed in RED or BLUE or any other color. For example I have a list of fruits and I am searching for Apple, so when I start typing app... le, then the color of only those characters which are typed by the user, app (in this case), should be changed to RED, BLUE or any other color if the item Apple is present in the list.

Can anyone tell whether this is possible to do in Android and if yes, then how to do so. Thanks in Advance

like image 743
swdeveloper Avatar asked Jan 16 '14 13:01

swdeveloper


1 Answers

The more simply way to do that is to register a 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){}
});

Then we must reload the ListView, can use notifyDataSetChanged() on the adapter (something must change to fire event)

myListViewAdapter.notifyDataSetChanged()

Finally in the adapter:

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

Notice that this code must be adjusted for performance and logic but this can be a good startup.

like image 155
phemt.latd Avatar answered Oct 22 '22 05:10

phemt.latd