android 滑動或者點選其他地方隱藏鍵盤的方法,
阿新 • • 發佈:2018-11-09
/** * 設定滑動隱藏鍵盤的操作 *parentView 最外層的父佈局,主要用於隱藏鍵盤 *mSendText,某個按鈕,比如傳送按鈕,避免也當隱藏鍵盤處理,不過這裡isShouldHideKeyboard限制了只能進入EditText,所以暫時不起作用,有要做處理的可以把isShouldHideKeyboard 的 if (v != null && (v instanceof EditText))優化以下 */ public boolean setDisTouchHidKeyBord(MotionEvent ev, View parentView, TextView mSendText, Context context) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { View v = getCurrentFocus(); if (AppUtil.isShouldHideKeyboard(v, ev)) { AppUtil.hideKeyboard(v.getWindowToken(), parentView, context); if (mSendText==null)return super.dispatchTouchEvent(ev); if (!AppUtil.isShouldHideKeyboard(mSendText, ev)) { return super.dispatchTouchEvent(ev); } return true; } } else if (ev.getAction() == MotionEvent.ACTION_MOVE) { View v = getCurrentFocus(); AppUtil.hideKeyboard(v.getWindowToken(), parentView, context); } return super.dispatchTouchEvent(ev); }
/** * 根據EditText所在座標和使用者點選的座標相對比(這裡都是相對於螢幕),來判斷是否隱藏鍵盤,因為當用戶點選EditText時則不能隱藏 * * @param v * @param event * @return */ public static boolean isShouldHideKeyboard(View v, MotionEvent event) { if (v != null && (v instanceof EditText)) {//如果edittext獲取焦點的時候 int[] l = {0, 0}; v.getLocationInWindow(l); int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth(); /* LogUtil.e("left=+"+left); LogUtil.e("top=+"+top); LogUtil.e("bottom=+"+bottom); LogUtil.e("right=+"+right); LogUtil.e("event.getX()=+"+event.getRawX()); LogUtil.e("event.getY()=+"+event.getRawY());*/ if (event.getRawX() > left && event.getRawX() < right && event.getRawY() > top && event.getRawY() < bottom) { // 點選EditText的事件,忽略它。 return false; } else { return true; } } // 如果焦點不是EditText則忽略,這個發生在檢視剛繪製完,第一個焦點不在EditText上,和使用者用軌跡球選擇其他的焦點 return false; }
/** * 獲取InputMethodManager,隱藏軟鍵盤 * @param token */ public static void hideKeyboard(IBinder token, View parentView, Context context) { if (token != null) { parentView.setFocusable(true); parentView.setFocusableInTouchMode(true); parentView.requestFocus(); InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS); } }
//在activity中呼叫
@Override public boolean dispatchTouchEvent(MotionEvent ev) { return setDisTouchHidKeyBord(ev,parentView,null,BankOrderActivity.this); }