Search code examples
androidstringandroid-edittexttextviewautocompletetextview

Text box with suggestions


I am currently using an AutoCompleteTextView with a list of terms that gives suggestions as a user is typing. However, I want to use a different string algorithm than simply checking if a string contains your search term, that compares how close two strings are (e.g. searching "chcken" should show "chicken").

I have produced a method that takes a string parameter - your search query - and returns a sorted array of strings in the database that match that query based on relevance. How do I let the AutoCompleteTextView use that array? I can't simply attach it to the adapter with every keystroke, because that doesn't change the inherent behavior of the AutoCompleteTextView for only showing elements inside the array that MATCH the string query.


Solution

  • You can implement a custom filter in your adapter.

    Example:

    public class MyFilterableAdapter extends ListAdapter<String> implements Filterable {
    
        @Override
        public Filter getFilter() {
            return new Filter() {
                @Override
                public String convertResultToString(Object resultValue) {
                    return (String) resultValue;
                }
    
                @Override
                protected FilterResults performFiltering(CharSequence constraint) {
                    FilterResults filterResults = new FilterResults();
                    filterResults.values = filteredArray;
                    filterResults.count = filteredArray.size();
                    return filterResults;
                }
    
                @Override
                protected void publishResults(CharSequence constraint, FilterResults results) {
                    if (results != null && results.count > 0) {
                        //here you will need to update the array where you are controlling what shows in the list
                        notifyDataSetChanged();
                    }
                }
            };
        }
    }
    

    Since you did not provided any code, I don't know what adapter you are using, but you will need to implement all the adapter method (getCount, getView, etc).

    You can find more info in those questions:

    How to create custom BaseAdapter for AutoCompleteTextView

    Autocompletetextview with custom adapter and filter