1. 程式人生 > >開啟關閉軟鍵盤,點選螢幕其他地方關閉軟鍵盤

開啟關閉軟鍵盤,點選螢幕其他地方關閉軟鍵盤

開啟關閉軟鍵盤,點選螢幕其他地方關閉軟鍵

關閉然鍵盤:
public void closeKeyboard() {
    View rootView = getWindow().getDecorView();
    closeKeyboard(rootView);
}
public void closeKeyboard(View view) {
    InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View v = getCurrentFocus();
    if (v != null && im.isActive()) {
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        view.requestFocus();
        im.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

開啟軟鍵盤:
public void openKeyboard(View v) {
v.requestFocus();
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.showSoftInput(v, 0);
}
點選螢幕其他地方關閉然鍵盤:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    if (ev.getAction() == MotionEvent.ACTION_DOWN) {
        View v = getCurrentFocus();
        if (v != null) {
            Log.e("v", "v = " + v.getClass().getSimpleName());
        }
        if (isShouldHideKeyboard(v, ev)) {
            closeKeyboard();
        }
    }
    return super.dispatchTouchEvent(ev);
}

/**
 * 根據EditText所在座標和使用者點選的座標相對比,來判斷是否隱藏鍵盤,因為當用戶點選EditText時則不能隱藏
 *
 * @param v
 * @param event
 * @return
 */
public boolean isShouldHideKeyboard(View v, MotionEvent event) {
    if (v != null && (v instanceof EditText)) {
        return !isTouchView(v, event);
    }
    // 如果焦點不是EditText則忽略,這個發生在檢視剛繪製完,第一個焦點不在EditText上,和使用者用軌跡球選擇其他的焦點
    return false;
}

//是不是點選在view上
public boolean isTouchView(View v, MotionEvent event) {
int[] l = {0, 0};
v.getLocationInWindow(l);
int left = l[0],
top = l[1],
bottom = top + v.getHeight(),
right = left + v.getWidth();
return event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom;
}