SoFunction
Updated on 2025-04-09

Android AutoCompleteTextView control usage example


AutoCompleteTextView autoComplete = new AutoCompleteTextView(context);
(2);      // Setting at least a few characters to trigger automatic completion
MyAdapter adapter = new MyAdapter(context);
(adapter);

/**
* Adapter definition
 */
class MyAdapter extends ArrayAdapter<MyObject> implements Filterable{

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
// define your list item view here Define the view of the list item here
    }

    /**
* Implement an automatic filtering algorithm
     */
    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {

            /**
* This method is executed in a background thread and defines a filtering algorithm
             */
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                String keyword = (constraint).toLowerCase();
// Filtering is implemented here

// After filtering, use FilterResults to return the filtered result
                FilterResults filterResults = new FilterResults();
= results;   // results are the filtering result above
= ();  // Number of results

                return filterResults;
            }

            /**
* This method is executed in the UI thread and is used to update the automatic completion list
             */
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {
                if (results != null && > 0) {
// There are filtering results, displaying the automatic completion list
();    // Clear the old list
                    ((List<MyObject>));
                    notifiDataSetChanged();
                } else {
// No filtering results, close the list
                    notifyDataSetInvalidated();
                }
            }

            /**
* If you need to control the display of prompt text, overload this function
             */
            @Override
            public CharSequence convertResultToString(Object resultValue) {
                MyObject obj = (MyObject) resultValue;
                return ;
            }

        };
    }
}