简体   繁体   中英

Filtering AutoCompleteTextView to show partial match

Right now I have an AutoCompleteTextView and I want it to work just like the like "%xxx%" does in SQL. I attempted to do it using Filterable I have it and the code runs but it just displays everything now even if there is no partial match. Any help would be appreciated.

public class CodesArrayAdapter extends ArrayAdapter implements Filterable{

    List<String> allCodes;
    List<String> originalCodes;

    StringFilter filter;


    public CodesArrayAdapter(Context context, int resource, List<String> keys) {
        super(context, resource, keys);

        allCodes=keys;
        originalCodes=keys;


    }

    public int getCount() {
        return allCodes.size();
    }

    public Object getItem(int position) {
        return allCodes.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    private class StringFilter extends Filter {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {

            String filterString = constraint.toString().toLowerCase();

            FilterResults results = new FilterResults();

            final List<String> list = originalCodes;

            int count = list.size();
            final ArrayList<String> nlist = new ArrayList<String>(count);

            String filterableString ;

            for (int i = 0; i < count; i++) {
                filterableString = list.get(i);
                if (filterableString.toLowerCase().contains(filterString)) {
                    nlist.add(filterableString);
                }
            }

            results.values = nlist;
            results.count = nlist.size();

            return results;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
            allCodes = (ArrayList<String>) results.values;
            notifyDataSetChanged();
        }

    }
}

If this is the complete code of your adapter, you just missed implementing the getFilter() method, ie

@Override
public Filter getFilter()
{
    return new StringFilter();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM