Android:限制用户选择自动完成建议以外的选项? [英] Android: Restrict user from selecting other than autocompletion suggestions?
问题描述
我提供了一个 AutoCompleteTextView
来向用户显示建议.根据用户选择的项目,我获取项目的 ID 并在数据库端使用它.现在我的问题是强制用户仅从 AutoCompleteTextView
进行选择(即用户不应输入他自己的文本).这是客户的要求.如何做到这一点?
I have provided an AutoCompleteTextView
to show suggestions to the user. Based on the item selected by the user, I am getting the ID of the item and using it in data base side. Now my problem is to force the user to make selection only from AutoCompleteTextView
(i.e. user should not enter his own text). It is a client requirement. How to do this?
推荐答案
这是一个非常简单的解决方案:
Here's a pretty straightforward solution:
您可以通过在 AutoCompleteTextView
中设置 setOnItemClickListener
来创建一个变量来存储所选值.然后,只要用户在该字段中键入,就可以通过向该字段添加 TextWatcher
来null
该值.最后,您可以在继续之前验证您的变量不为空.
You can create a variable to store the selected value by setting setOnItemClickListener
in your AutoCompleteTextView
. Then you can null
that value whenever a user types in the field by adding a TextWatcher
to it. Finally, you can validate your variable is not null before continuing.
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) {}
});
这篇关于Android:限制用户选择自动完成建议以外的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!