AutoCompleteTextView 将选项限制为仅适用于为其设置的适配器中的选项,并且在列表可见之前不需要两个字符

AutoCompleteTextView that limits options to just those in the adapter set for it and doesn't require two characters before the list is visible

我想使用 AutoCompleteTextView 来提供一个选项列表,这样当用户点击它时,他们会得到完整的列表,但是当他们输入它时,他们会在搜索特定项目时减少项目的数量.其次,它需要将条目限制为仅提供适配器中可用的选项。

为什么 AutoCompleteTextView 不这样做呢?因为你必须在列表出现之前输入两个字符,所以我希望这个列表在 TextView 获得焦点时可以滚动。

xml代码:

<AutoCompleteTextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:ems="10"
        android:maxLines="1"
        android:inputType="text" />

这是我目前拥有的,它容易受到我上面描述的问题的影响。

java代码:

    List<String> typeList = new ArrayList<>();
    for (int i = 0; i < items.size(); i++){
        typeList.add(i, items.get(i).getName());
    }
    String[] descriptions = typeList.toArray(new String[0]);

    final ArrayAdapter<String> autoCompleteAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, names);
    final AutoCompleteTextView categoryInput = (AutoCompleteTextView) view.findViewById(R.id.autoCompleteCategory);

好的!设法找出一个解决方案,最后很简单,将 OnFocusChangeListener() 添加到 AutoCompleteTextView 然后如果视图有焦点,则执行 showDropDown()

这样一来,任何人只要点击它,就会立即获得完整的列表,而且随着他们的输入,列表的大小会缩小。

As you written this : Because you have to type two characters in before the list even appears

如果我没有理解错,您正在寻找如何在键入两个或更多字符后设置列表。

您可以通过 xml android:completionThreshold="2" 进行设置 或者您可以通过编程方式设置,

使用setThreshold().

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.

您必须重写 AutoCompleteTextView 中的 enoughToFilter() 方法,以在用户输入至少 1 或 2 个字符的情况下实现过滤。

基本上通过扩展 AutoCompleteTextView 并始终将 enoughtToFilter() 方法覆盖为 return true 来创建您自己的自定义视图。

public class CustomAutoCompleteTextView extends AutoCompleteTextView {

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

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

    public CustomAutoCompleteTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean enoughToFilter() {
        return true;
    }

}