我正在使用AutoCompleteTextView
。當用戶輸入AutoCompleteTextView
時,我會得到一些結果,這些都是強制選擇的。 但問題是,當在srceen中的任何地方點擊時,下拉菜單會自動解除。 我想避免這種情況。 有什麼辦法可以做到這一點。如何限制AutoCompleteTextView下拉菜單關閉?
謝謝。
我正在使用AutoCompleteTextView
。當用戶輸入AutoCompleteTextView
時,我會得到一些結果,這些都是強制選擇的。 但問題是,當在srceen中的任何地方點擊時,下拉菜單會自動解除。 我想避免這種情況。 有什麼辦法可以做到這一點。如何限制AutoCompleteTextView下拉菜單關閉?
謝謝。
請嘗試下面的代碼。
我正在使用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()方法防止從打字不你的字符串數組中存在,例如文本的用戶:如果用戶鍵入「德國‘這是你的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();
}
}
}
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
,但 - 也許這不是一個太好的解決方案
@Andreyua試試https://matalamaki.fi/2015/09/07/android-autocompletetextview-with-drop-down-always-visible-or-how-to-figure-your-way-with-internal- Android系統的API /。另一種方法是在'onTouchEvent(MotionEvent event)'內部調用'autoTextView.showDropDown();',但它不是美麗的效果:) – BNK
如果下拉是可見的,你可以保留一個變量來跟蹤並在你的activity中實現onTouchEvent 。如果下拉菜單可見,則返回true,並且不要調用super超級呼叫。也許它會工作,但它不是一個好的解決方案 –