3

In Android AutoCompleteTextView only show show dropdown when we entered first letter correctly .What I want is when I enter any letter sequence in the string available it should show the drop down.for example "January" is in my array so when i enter "anu" in AutoComplete field it should show "january" in drop down.Please help. Thank You

Piyush Agarwal
  • 25,608
  • 8
  • 98
  • 111
  • I am doing something similar HERE!!! http://stackoverflow.com/questions/12854336/autocompletetextview-backed-by-cursorloader – Etienne Lawlor Oct 29 '12 at 20:05

1 Answers1

1

You are likely going to have write your own Filter and attach it via a TextWatcher. This response has an example of regex in an AutoCompleteTextView: Android AutoCompleteTextView with Regular Expression? and here is another regex/java example: How can I perform a partial match with java.util.regex.*?

EDIT: You will need to extend ArrayAdapter in order to override getFilter() and return your custom filter.

So you are going to have something like this:

autoCompleteTextView.setAdapter(arrayAdapter);
autoCompleteTextView.addTextChangedListener(new TextWatcher() {
   public void onTextChanged(CharSequence s, int start, int before, int count) {
      arrayAdapter.getFilter().filter(s);
   }
});

public class RegexFilter extends Filter{

   ArrayAdapter<String> mAdapter;
   public RegexFilter(ArrayAdapter<String> adapter) {
      mAdapter = adapter;
   }
...
   @Override
   protected FilterResults performFiltering(CharSequence constraint) {
      Pattern p = Pattern.compile(constraint);
      Matcher m = p.matcher("");
      List listOfMatches = new ArrayList<String>();
      for (String curMonth : months) {
         m.reset(curMonth);
         if (m.matches || m.hitEnd()) {
            listOfMatches.add(curMonth);
         }
      }
      FilterResults results = new FilterResults();
      results.values = listOfMatches;
      results.count = listOfMatches.size();
      return results;
   }

   @Override
   protected void publishResults(CharSequence constraint, FilterResults results) {
      mAdapter.addAll(results.values);
      mAdapter.notifyDataSetChanged();
   }
}

public class PartialArrayAdapter extends ArrayAdapter<String> {
   ...
   RegexFilter mFilter;
   @Override
   public TimedSuggestionFilter getFilter() {
      if(null == mFilter)
         mFilter = new RegexFilter(this);
      return mFilter;
   }
Community
  • 1
  • 1
Salil Pandit
  • 1,498
  • 10
  • 13
  • Sorry but i am not able to find setFilter() and getFilter() functions in AutoCompleteTextView Class.my android API Level is 8 – Piyush Agarwal Mar 10 '12 at 22:31
  • @pyus13 edited my code. Sorry the getFilter() function is in ArrayAdapter. I recommend doing an ArrayAdapter example (maybe like this one: http://sudarmuthu.com/blog/using-arrayadapter-and-listview-in-android-applications). Adapters are an important part of Android... – Salil Pandit Mar 11 '12 at 02:59