Android 之關閉軟鍵盤

 
第一種方法:
 
//直接關閉鍵盤輸入法
private void closeInputMethod() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    boolean isOpen = imm.isActive();
    if (isOpen) {
        // imm.toggleSoftInput(0,
        // InputMethodManager.HIDE_NOT_ALWAYS);//沒有顯示則顯示
        imm.hideSoftInputFromWindow(edt_pass.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}
 

 
第二種方法:
 
//點擊空白收起鍵盤
 
@Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            // 得到當前獲得焦點的View,通常狀況下就是EditText(特殊狀況就是軌跡求或者實體案件會移動焦點)
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }
 
    /**
     * 根據EditText所在座標和用戶點擊的座標相對比,來判斷是否隱藏鍵盤,由於當用戶點擊EditText時不必隱藏
     *
     * @param v
     * @param event
     * @return
     */
    private boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = { 0, 0 };
            v.getLocationInWindow(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 點擊EditText的事件,忽略它。
                return false;
            } else {
                return true;
            }
        }
        // 若是焦點不是EditText則忽略,這個發生在視圖剛繪製完,第一個焦點不在EditView上,和用戶用軌跡球選擇其餘的焦點
        return false;
    }
 
    /**
     * 多種隱藏軟件盤方法的其中一種
     *
     * @param token
     */
    private void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
 

 
第三種方法:
 
//列表頁,滾動收起軟鍵盤
listGoods.setOnTouchListener(new View.OnTouchListener() {
 
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        ((InputMethodManager) mContext.getSystemService(mContext.INPUT_METHOD_SERVICE))
                .hideSoftInputFromWindow(v.getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        return false;
    }
});
相關文章
相關標籤/搜索