Android 點擊EditText外部區域隱藏小鍵盤

1.顯示與隱藏鍵盤的方法

/**
     * 顯示鍵盤
     * @param edit 輸入焦點
     */
    public void showInputKeyboad(final EditText edit) {
        edit.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);

    }
    /**
     * 隱藏鍵盤
     */
    protected void hideInputKeyboad() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = this.getCurrentFocus();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

2.重寫Activiity中的方法

@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isSoftShowing() && isShouldHideInput(v, ev)) {
                hideInputKeyboad();
            }
        }
        return super.dispatchTouchEvent(ev);
    }

3.判斷軟鍵盤是否正在展示

private boolean isSoftShowing() {
        //獲取當前屏幕內容的高度
        int screenHeight = getWindow().getDecorView().getHeight();
        //獲取View可見區域的bottom
        Rect rect = new Rect();
        getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        return screenHeight - rect.bottom != 0;
    }

4.是否需要隱藏鍵盤

public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //獲取輸入框當前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            if (event.getY() > top) {
                // 點擊的是輸入框上方區域
                return false;
            } else {
                return true;
            }
        }
        return false;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章