jramirez
jramirez

Reputation: 484

Limit AutoCompleteTextView to only one result

I'm using AutoCompleteTextView with a custom layout for the adapter. The problem is I don't know how to limit the results for only one at time, like in the default Layout. I read that It's possible limiting the height, but doesn't work in all screens. Thanks for your attention.

I've this on my activity_main layout.

<AutoCompleteTextView android:id="@+id/autotext" 
android:layout_width="0dp" 
android:layout_height="wrap_content"
android:minWidth="480dp" 
android:layout_weight="1" 
android:maxLength="23" 
android:maxLines="1" 
android:textColor="#000000" />

And this is the adapter's layout.

<TextView android:id="@+id/textpop" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="17sp"/>

Upvotes: 2

Views: 3819

Answers (3)

Hexise
Hexise

Reputation: 1568

You can create your own AutoCompleteTextView adapter which implement Filterable interface, or extend existing adapter, but override getFilter() method, create your own filter implementation, then you can customize filter logic and return any number of results you like.

You can refer to the ArrayFilter implementation in ArrayAdpater for reference.

Upvotes: 0

AidenFry
AidenFry

Reputation: 278

I found the above answer unsatisfactory, and the link is dead.

For the simplest way to do this, create a custom adapter and simply force the count to 1

class SingleArrayAdapter extends ArrayAdapter<String> {

        public SingleArrayAdapter(Context context, int resource, String[] objects) {
            super(context, resource, objects);
        }

        @Override
        public int getCount() {
            return 1;
        }
    }

Upvotes: 0

user
user

Reputation: 87064

Have a look at this code. It's basically the code for the SDK ArrayAdapter class with a small modification(which doesn't count). If you want to show only one suggestion in the AutoCompleteTextView then you could make a small modification to the class from the link, to the performFiltering() method like this:

// ... the rest of that method
if (newValues.size() > 1) { // if we have more than an item in the list
    // get the first suggestion
    T oneItem = newValues.get(0);
    // empty the suggestion list
    newValues.clear();
    // add the only suggestion.
    newValues.add(oneItem);
}
results.values = newValues;
results.count = newValues.size();

Upvotes: 2

Related Questions