我正在使用AutoCompleteTextView.当用户输入AutoCompleteTextView时,我会得到一些结果,这些是必须选择的.
但问题是当点击srceen的任何地方时,下拉自动解除.
我想避免这个.
有什么方法可以实现这一点.
但问题是当点击srceen的任何地方时,下拉自动解除.
我想避免这个.
有什么方法可以实现这一点.
谢谢.
解决方法
尝试下面的代码.
我使用AutoCompleteText自动完成用户当前所在的位置,locationList只是我在strings.xml文件中编写的数组,所以在这里使用自己的字符串数组.
locationList = res.getStringArray(R.array.ticketLocation);
ArrayAdapter<String> locationAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,locationList);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtCountries);
textView.setThreshold(1);
textView.setAdapter(locationAdapter);
textView.setValidator(new Validator());
textView.setonFocuschangelistener(new FocusListener());
textView.setonItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,View view,int position,long id) {
// Todo Auto-generated method stub
TextView ticketLocation = (TextView) view;
getTicketLocation = ticketLocation.getText().toString();
}
});
以下是用于验证位置字段中输入文本的代码,fixText()方法阻止用户键入字符串数组中不存在的文本,例如:如果用户键入“germany”,则不存在于你的字符串数组列表,它将被替换为“”,这是你的edittext输入字段中的空字符串
class Validator implements AutoCompleteTextView.Validator {
@Override
public boolean isValid(CharSequence text) {
// Log.v("Test","Checking if valid: " + text);
Arrays.sort(locationList);
if (Arrays.binarySearch(locationList,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.txtCountries && !hasFocus) {
// Log.v("Test","Performing validation");
((AutoCompleteTextView) v).performValidation();
}
}
}