Dru*_*lic 14 validation android autocompletetextview
有没有办法强制autocompletetextview中的条目成为条目列表中的元素之一?
我找到了一个名为"performValidation"的方法,但我不确定它实际上做了什么,而且我还没有找到很多文档或任何示例.
rog*_*rkk 22
该AutoCompleteTextView有一个称为方法setValidator(),是以界面的一个实例AutoCompleteTextView.Validator作为参数.AutoCompleteTextView.Validator包含isValid()用于检查已输入值的内容,您可以通过实现"修复"此字符串fixText().
似乎这是你能得到的最好的AutoCompleteTextView,作为AutoCompleteTextView.Validator以下状态的文档:
"由于没有万无一失的方法来阻止用户使用不正确的值离开此视图,我们所能做的就是在发生这种情况时尝试自行解决."
如果你的元素列表不是太长,你可能最好使用Spinner.
******编辑:******
我在一起快速举例说明如何使用它,希望它有所帮助!
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<AutoCompleteTextView
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Focus me to validate above text"/>
</LinearLayout>
Run Code Online (Sandbox Code Playgroud)
-
public class AutoCompleteTextViewActivity extends Activity {
String[] validWords = new String[]{"", "snowboard", "bobsleigh", "slalom"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AutoCompleteTextView view = (AutoCompleteTextView)findViewById(R.id.input);
view.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, validWords));
view.setValidator(new Validator());
view.setOnFocusChangeListener(new FocusListener());
}
class Validator implements AutoCompleteTextView.Validator {
@Override
public boolean isValid(CharSequence text) {
Log.v("Test", "Checking if valid: "+ text);
Arrays.sort(validWords);
if (Arrays.binarySearch(validWords, text.toString()) > 0) {
return true;
}
return false;
}
@Override
public CharSequence fixText(CharSequence invalidText) {
Log.v("Test", "Returning fixed text");
/* I'm just returning an empty string here, so the field will be blanked,
* but you could put any kind of action here, like popping up a dialog?
*
* Whatever value you return here must be in the list of valid words.
*/
return "";
}
}
class FocusListener implements View.OnFocusChangeListener {
@Override
public void onFocusChange(View v, boolean hasFocus) {
Log.v("Test", "Focus changed");
if (v.getId() == R.id.input && !hasFocus) {
Log.v("Test", "Performing validation");
((AutoCompleteTextView)v).performValidation();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13699 次 |
| 最近记录: |