33

我提供了一个AutoCompleteTextView向用户显示建议。根据用户选择的项目,我正在获取项目的 ID 并在数据库端使用它。现在我的问题是强制用户只从AutoCompleteTextView(即用户不应该输入他自己的文本)中进行选择。这是客户的要求。这个怎么做?

4

9 回答 9

34

这是一个非常简单的解决方案:

您可以通过setOnItemClickListenerAutoCompleteTextView. 然后null,只要用户在字段中键入,您就可以通过添加 aTextWatcher来获得该值。最后,您可以在继续之前验证您的变量不为空。

String my_var; //keep track!
AutoCompleteTextView tv = (AutoCompleteTextView) layout.findViewById(R.id.tv);
tv.setAdapter(my_adapter);  
tv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        my_var = my_adapter.getItem(position).toString();
    }
});
/**
 * Unset the var whenever the user types. Validation will
 * then fail. This is how we enforce selecting from the list.
 */
tv.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        my_var = null;
    }
    @Override
    public void afterTextChanged(Editable s) {}
});
于 2013-03-26T22:08:32.450 回答
21

对于我正在从事的项目,我碰巧需要这样的要求,尽管我会以我实现所需的方式与大家分享。

我为自动完成文本视图添加了焦点更改侦听器,并检查了用户何时从自动完成中更改了焦点,并直接处理了这种情况。

autoTextViewCountry.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            if(!b) {
                // on focus off
                String str = autoTextViewCountry.getText().toString();

                ListAdapter listAdapter = autoTextViewCountry.getAdapter();
                for(int i = 0; i < listAdapter.getCount(); i++) {
                    String temp = listAdapter.getItem(i).toString();
                    if(str.compareTo(temp) == 0) {
                        return;
                    }
                }

                autoTextViewCountry.setText("");

            }
        }
    });

所以我的实现是:如果数组适配器中不存在键入的文本,则焦点更改为空文本视图,然后在继续说注册的下一阶段时,检查此文本视图是否为空。

希望这种方法可以帮助某人。

快乐编码。

于 2015-06-03T21:28:29.690 回答
4

NiceAutoCompleteTextView将使您能够检查是否从下拉弹出窗口中进行了选择,方法是调用isSelectionFromPopup()

于 2016-01-29T03:20:21.857 回答
2

只需将此属性添加到您的 AutoCompleteTextView。

安卓:可聚焦=“假”

我的代码如下所示:

        <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/menu"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Mode">

        <AutoCompleteTextView
            android:id="@+id/mode"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:focusable="false"
            />

    </com.google.android.material.textfield.TextInputLayout>

在 Java 方面:

AutoCompleteTextView mode = findViewById(R.id.mode);
   final List<String> modeList = new ArrayList();
    modeList.add("YEARLY");
    modeList.add("HALF-YEARLY");
    modeList.add("QUARTER-YEARLY");
    modeList.add("MONTHLY");
    mode.setAdapter(new ArrayAdapter(getApplicationContext(),R.layout.list_item,modeList));

获取 AutoCompleteTextView 的文本:

mode.getText().toString()
于 2021-03-20T04:03:16.470 回答
1

好的,我假设您希望将用户的输入限制为建议框中列出的项目列表中包含的文本。

例如,如果您有:

那么用户只能输入第一个字符“O”和“T”。依此类推之前输入的文字。

为此,您可以利用TextView的setFilters方法:

editBox = (TextView) findViewById(R.id.editBox);
editBox.setFilters(getFilters());
editBox.addTextChangedListener(this);
editBox.setOnFocusChangeListener(this);

此外,您可能需要文本更改侦听器和焦点侦听器在输入新字符时做出反应并更新过滤列表......加上更新过滤器。

这是我在项目中使用的十进制数过滤器的示例:

protected InputFilter[] getFilters()
    {
        InputFilter[] filters = new InputFilter[1];

        filters[0] = new InputFilter()
        {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend)
            {
                // limit input to digits and decimal / thousand separator only
                // in case thousand separator is pressed, change it to decimal
                // separator instead
                String output = "";

                if (number.isFocused())
                {
                    for (int i = start; i < end; i++)
                    {
                        char c = source.charAt(i);

                        if (isDecimalOrThousandSeparator(c))
                        {
                            output = output + Character.toString(decimalSeparator);
                        }
                        else if (Character.isDigit(c))
                        {
                            output = output + Character.toString(c);
                        }
                    }

                    return output == "" ? null : output;
                }

                return null;
            }
        };

        return filters;
    }
于 2012-11-16T07:24:53.680 回答
1

这是该专业AutoCompleteTextView.Validator人士确保有效值的另一种解决方案。当编辑文本失去焦点时调用验证器。

autoCompleteTextView.validator = object : AutoCompleteTextView.Validator {
        override fun isValid(text: CharSequence?): Boolean {
            return optionsList.contains(text.toString())
        }

        override fun fixText(invalidText: CharSequence?): CharSequence {
            return ""
        }
    }

optionsList有效值列表在哪里。

于 2020-10-20T07:25:37.637 回答
1

一个简单的解决方案是只检查当前输入是否是适配器中的项目之一。你可以这样做:

val AutoCompleteTextView.isValid: Boolean
    get() {
        for (i in 0 until adapter.count) {
            if (adapter.getItem(i) == text.toString()) {
                return true
            }
        }

        return false
    }
于 2020-03-26T08:59:18.987 回答
1

我有同样的要求,所以这是我的实现:

autoCompleteTextView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                autoCompleteTextView.showDropDown();
            }
        });

在 xml 集focusable=falsefocusableInTouchMode=false.

快乐编码

于 2020-10-28T13:55:48.993 回答
0

为了使 AutoCompleteTextView 具有不可编辑的变体,您应该在 AutoCompleteTextView 中禁用用户输入。这可以通过在 AutoCompleteTextView 上设置 android:inputType="none" 来实现。

于 2020-10-29T08:30:01.703 回答