如何通过单击EditText外部来隐藏虚拟键盘?

时间:2011-10-03 17:39:41

标签: android android-virtual-keyboard

我是Android开发的新手。我的要求是当我点击EditText小部件的外部时我想要隐藏android虚拟键盘。请帮忙。

2 个答案:

答案 0 :(得分:5)

要隐藏虚拟键盘,您可以执行以下代码:

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

只需将该代码放在与父布局绑定的onTouchDown() OnTouchListener方法中。

答案 1 :(得分:3)

请检查一下。

@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;
}

重写此方法,您可以在活动中编辑文字。