Hide keyboard when down arrow is pressed
The picture shows a part of my app, an AutoCompleteTextView
with an attached adapter. When the user enters something into that view, autocomplete suggestions are shown.
The problem I have is: when the suggestions are shown and the device's down arrow is pressed, only the suggestions from the AutoCompleteTextView
are closed, the keyboard stays open and needs a second tap on the down arrow to disappear.
I do want the suggestions and the keyboard to disappear on the first tap on the down arrow.
I tried overriding onBackPressed
but it is not called when the down arrow is tapped, presumably because it's not considered 'back'.
How could I do this?
EDIT : I know how to programmatically hide the keyboard, I guess my problem is to detect the 'down arrow' tap.
尝试在您的AutoCompleteTextView中覆盖onKeyPreIme()
方法,如下所示:
@Override
public boolean onKeyPreIme(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == 1) {
super.onKeyPreIme(keyCode, event);
hideKeyboard()
return true;
}
return super.onKeyPreIme(keyCode, event);
}
You can try something like this:
private boolean mIsKeyboardShown;
private EditText mSearchTextView;
@Override
protected void onCreate(Bundle bundle)
...
mSearchTextView = (EditText) findViewById(R.id.search);
View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
// if more than 100 pixels, its probably a keyboard...
mIsKeyboardShown = (heightDiff > 100);
}
});
}
public void onBackPressed() {
if(mIsKeyboardShown) {
// close the keyboard
InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(mSearchTextView.getWindowToken(), 0);
} else {
super.onBackPressed();
}
}
I haven't tried the code but I think this is the right approach.
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
你需要导入android.view.inputmethod.InputMethodManager;
下一篇: 按下向下箭头时隐藏键盘