问题
I am new to Android development. My requirement is that I want to hide the android virtual keypad when I click on the outside of an EditText widget. Please help.
回答1:
To hide the virtual keyboard you can execute the following code:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
Simply put that code inside the onTouchDown()
method of an OnTouchListener
that is tied to the parent layout.
回答2:
Just check this.
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
View view = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);
if (view instanceof EditText) {
View w = getCurrentFocus();
int scrcoords[] = new int[2];
w.getLocationOnScreen(scrcoords);
float x = event.getRawX() + w.getLeft() - scrcoords[0];
float y = event.getRawY() + w.getTop() - scrcoords[1];
if (event.getAction() == MotionEvent.ACTION_UP
&& (x < w.getLeft() || x >= w.getRight()
|| y < w.getTop() || y > w.getBottom()) ) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
}
}
return ret;
}
Override this method where you have edit text in your activity..
来源:https://stackoverflow.com/questions/7638607/how-to-hide-the-virtual-keypad-by-clicking-outside-of-an-edittext