Android:如何在强制打开时强制关闭软键盘?

Android:How do I force the soft keyboard to close when it has been forced to open?

我的Activity中有一个EditText。 一旦Activity开始,我就强制使用软键盘打开。

1
2
3
4
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

现在,如果软键盘打开,我按下主页按钮,它仍保持打开状态。 如何在家用印刷机上强行关闭它?


1
2
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(Your Button.getWindowToken(), 0);


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@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];

        // Log.d("Activity","Touch event"+event.getRawX()+","+event.getRawY()+""+x+","+y+" rect"+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords"+scrcoords[0]+","+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;
}

当您触摸屏幕上的任何位置时,此代码会关闭键盘。