user716263
user716263

Reputation: 1

Android AutoCompleteTextView

When I type a on EditText, I want to let addacer、...show in the drop down menu. I know it can complete with AutoCompleteTextView. But I want it also show batcat..., the string a is in a word, not in the front.

Upvotes: 0

Views: 380

Answers (2)

heycosmo
heycosmo

Reputation: 1398

It looks like you have to implement your own Filter class. You then have to implement a ListAdapter (that wraps your list of strings) which also implements the Filterable interface; this subclass should return your custom Filter when getFilter is called. You pass your custom ListAdapter/Filterable into an AutoCompleteTextView via the setAdapter() method. (An easy way to do all this is to subclass Android's ArrayAdapter.)

Here's the source code for the ArrayAdapter. Find the definition of the ArrayFilter (at the bottom) and modify it to your needs. The following code is the ArrayFilter with a modification you might be looking for. You'll have to study the effects of mLock, mObjects, and mOriginalValues before applying to your own Adapter subclass.

private class ArrayFilter extends Filter {
    @Override
    protected FilterResults performFiltering(CharSequence prefix) {
        FilterResults results = new FilterResults();

        if (mOriginalValues == null) {
            synchronized (mLock) {
                mOriginalValues = new ArrayList<T>(mObjects);
            }
        }

        if (prefix == null || prefix.length() == 0) {
            ArrayList<T> list;
            synchronized (mLock) {
                list = new ArrayList<T>(mOriginalValues);
            }
            results.values = list;
            results.count = list.size();
        } else {
            String prefixString = prefix.toString().toLowerCase();

            ArrayList<T> values;
            synchronized (mLock) {
                values = new ArrayList<T>(mOriginalValues);
            }

            final int count = values.size();
            final ArrayList<T> newValues = new ArrayList<T>();
            for (int i = 0; i < count; i++) {
                final T value = values.get(i);
                final String valueText = value.toString().toLowerCase();

                if (valueText.contains(prefixString)) {
                    newValues.add(value);
                }
            }

            results.values = newValues;
            results.count = newValues.size();
        }

        return results;
    }

    @Override
    protected void publishResults(CharSequence constraint, FilterResults results) {
        //noinspection unchecked
        mObjects = (List<T>) results.values;
        if (results.count > 0) {
            notifyDataSetChanged();
        } else {
            notifyDataSetInvalidated();
        }
    }
}

Upvotes: 0

Ram kiran Pachigolla
Ram kiran Pachigolla

Reputation: 21201

Here is the same thing for what you are looking for..

Upvotes: 1

Related Questions