我正在研究一个AutoCompleteTextView
。当用户输入AutoCompleteTextView
时,我得到一些结果,这些结果是必须选择的。但问题是,当单击srceen中的任何位置时,下拉列表会自动关闭。我想避免这种情况。有什么办法可以做到这一点。
谢谢。
private boolean setForceIgnoreOutsideTouchWithReflexion(boolean forceIgnoreOutsideTouch) {
try {
Method method = android.widget.AutoCompleteTextView.class.getMethod("setForceIgnoreOutsideTouch", boolean.class);
method.invoke(this, forceIgnoreOutsideTouch);
return true;
} catch (Exception e) {
return false;
}
}
只有public class CustomAutoCompleteTextView extends AutoCompleteTextView
的反射,但是 - 也许这也不是一个好的解决方案
请尝试下面的代码。
我正在使用自动完成文本来自动完成用户当前所在的位置,locationList 只不过是我在字符串.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() 方法可防止用户键入字符串数组中不存在的文本,例如: 如果用户键入的"德国"在您的字符串数组列表中不存在,它将被替换为" ",这是您的 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();
}
}
}