hide default keyboard on click in android

后端 未结 10 841
忘掉有多难
忘掉有多难 2020-12-13 05:52

i want to hide the soft keyboard when i click out side of editbox in a screen. how can i do this?

10条回答
  •  难免孤独
    2020-12-13 06:04

    I added the following to my activity. It works because touching outside a Focusable View doesn't change the focus (so w == v) but the touch will be outside the View's rectangle.

    public boolean dispatchTouchEvent(MotionEvent event) {
        View v = getCurrentFocus();
        boolean ret = super.dispatchTouchEvent(event);
        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()) ) { 
            inputManager.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
        }
        return ret;
    
    }
    

    [edit: fix minor bug]

提交回复
热议问题