How to hide the virtual keypad by clicking outside of an EditText?

北慕城南 提交于 2019-12-11 06:26:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!