Android:是否限制用户选择自动完成建议以外的其他内容? [英] Android: Restrict user from selecting other than autocompletion suggestions?

查看:58
本文介绍了Android:是否限制用户选择自动完成建议以外的其他内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提供了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆