解決思路與iOS中的事件分發機制是類似的,這是Activity.class中的事件分發函數:
(1)下面的函數可以處理所有的點擊事件,但是要注意到不能無故攔截。
/** * Called to process touch screen events. You can override this to * intercept all touch screen events before they are dispatched to the * window. Be sure to call this implementation for touch screen events * that should be handled normally. * * @param ev The touch screen event. * * @return boolean Return true if this event was consumed. */ public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
(2)用戶布局文件中定義的元素都可以接受TouchEvent,下面的函數只是處理窗口之外空白區域的點擊。
/** * Called when a touch screen event was not handled by any of the views * under it. This is most useful to process touch events that happen * outside of your window bounds, where there is no view to receive it. * * @param event The touch screen event being processed. * * @return Return true if you have consumed the event, false if you haven't. * The default implementation always returns false. */ public boolean onTouchEvent(MotionEvent event) { if (mWindow.shouldCloseOnTouch(this, event)) { finish(); return true; } return false; }
因此,需要攔截點擊事件進行重新分發,在Activity的任意子類(含SDK或者用戶自定義的)中都可以重寫:
//點擊EditText以外的任何區域隱藏鍵盤 @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { View v = getCurrentFocus(); if (Utils.isShouldHideInput(v, ev)) { if(Utils.hideInputMethod(this, v)) { return true; //隱藏鍵盤時,其他控件不響應點擊事件==》注釋則不攔截點擊事件 } } } return super.dispatchTouchEvent(ev); }
public static boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] leftTop = { 0, 0 };
v.getLocationInWindow(l);
int left = leftTop[0], top = leftTop[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;
}
}
return false;
}
public static Boolean hideInputMethod(Context context, View v) { InputMethodManager imm = (InputMethodManager) context .getSystemService(Context.INPUT_METHOD_SERVICE); if (imm != null) { return imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } return false; }