Android, add() function of ArrayAdapter not working

后端 未结 3 742
栀梦
栀梦 2021-02-05 22:23

I have an ArrayAdapter (myAdapter) attached to an AutoCompleteTextView (textView) component.
Once the user presses a character I would like to populate AutoCompleteTextView\

3条回答
  •  故里飘歌
    2021-02-05 22:49

    I had the exact same problem. After examining the ArrayAdapter and AutoCompleteTextView source code, I found out that the problem was, in short, that:

    • the original object list is stored in ArrayAdapter.mObjects.
    • However, AutoCompleteTextView enables ArrayAdapter's filtering, meaning that new objects are added to ArrayAdapter.mOriginalValues, while mObjects contains the filtered objects.
    • ArrayAdapter.getCount() always returns the size of mObjects.

    My solution was to override ArrayAdapter.getFilter() to return a non-filtering filter. This way mOriginalValues is null and mObjects is used instead in all cases.

    Sample code:

    public class MyAdapter extends ArrayAdapter {
        NoFilter noFilter;
        /*
        ...
        */
    
        /**
         * Override ArrayAdapter.getFilter() to return our own filtering.
         */
        public Filter getFilter() {
            if (noFilter == null) {
                noFilter = new NoFilter();
            }
            return noFilter;
        }
    
        /**
         * Class which does not perform any filtering.
         * Filtering is already done by the web service when asking for the list,
         * so there is no need to do any more as well.
         * This way, ArrayAdapter.mOriginalValues is not used when calling e.g.
         * ArrayAdapter.add(), but instead ArrayAdapter.mObjects is updated directly
         * and methods like getCount() return the expected result.
         */
        private class NoFilter extends Filter {
            protected FilterResults performFiltering(CharSequence prefix) {
                return new FilterResults();
            }
    
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                // Do nothing
            }
        }
    }
    

提交回复
热议问题