Immediately show autocomplete on Android

2019-04-04 06:41发布

问题:

The Android autocomplete only starts after two letters. How can I make it so the list appears when the field is just selected?

回答1:

Extend the AutoCompleteTextView, overriding the enoughToFilter() methods and the threshold methods so that it doesn't replace the 0 threshold with a 1 threshold:

public class MyAutoCompleteTextView extends AutoCompleteTextView {

    private int myThreshold;

    public MyAutoCompleteTextView(Context context) {
        super(context);
    }

    public MyAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyAutoCompleteTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public void setThreshold(int threshold) {
        if (threshold < 0) {
            threshold = 0;
        }
        myThreshold = threshold;
    }

    @Override
    public boolean enoughToFilter() {
        return getText().length() >= myThreshold;
    }

    @Override
    public int getThreshold() {
        return myThreshold;
    }

}


回答2:

To get the autocomplete to show on focus add focus listener and show the drop down when the field gets focus, like this:

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
  @Override
  public void onFocusChange(View view, boolean hasFocus) {
    if(hasFocus){
      editText.showDropDown();
    }
  }
});

Or just call editText.showDropDown() if you don't need the focus part.



回答3:

Have a look to setThreshold method:

public void setThreshold (int threshold)
Since: API Level 1
Specifies the minimum number of characters the user has to type in the edit box before the drop down list is shown.
When threshold is less than or equals 0, a threshold of 1 is applied.



回答4:

Pad your adapter with one/two white character on left depending on the threshold setting.



回答5:

For people who want to change threshold using SearchView you have to use:

SearchView.SearchAutoComplete complete = (SearchView.SearchAutoComplete)search.findViewById(R.id.search_src_text);
complete.setThreshold(0);


回答6:

Alternate method of changing the setting in your XML: As mentioned by others you need to set your 'Auto Completion Threshold' to 1

Other than what @systempuntoout mentioned.

You can also do that in your XML file as shown

<AutoCompleteTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/edittext_id"
    android:inputType="textAutoComplete"
    android:completionThreshold="1"
/>

Note the line : android:completionThreshold="1"