最近項目中有個需求驱负,點擊某一個按鈕以外的位置觸發(fā)按鈕的點擊事件景图。 但是這整個view 都是第三方的宽气。?
通過父容器的dispatchTouchEvent(MotionEvent ev) 對事件進行控制和分發(fā)改化。
(1)找到要觸發(fā)的按鈕佩憾,獲取他的坐標 通過遞歸找到對應的控件
(2)判斷點擊是否在控件上
/**
* 判斷是否點擊在view上
*
* @param pointX
* @param pointY
* @param view
* @return
*/
private boolean isPointInView(float pointX, float pointY, View view) {
? ? if (view ==null) {
? ? ? ? return false;
? ? }
? ? int[] location =new int[2];
? ? view.getLocationOnScreen(location);
? ? int x = location[0];
? ? int y = location[1];
? ? if (pointX >= x && pointX <= x + view.getWidth() && pointY >= y && pointY <= y + view.getHeight()) {
? ? ? ? return true;
? ? }
? ? return false;
}
(3) 如果不在控件的位置哮伟,則通過傳遞 控件的MotionEvent 設置MotionEvent 的location ,分發(fā)child.dispatchTouchEvent 事件
private boolean dispatchChildTouchEvent(MotionEvent ev, View child) {
? ? MotionEvent transformedEvent = MotionEvent.obtain(ev);
? ? if (downPosX ==0 ||downPosY ==0) {
? ? ? ? int wd = Math.max(child.getWidth(), 1);
? ? ? ? int hg = Math.max(child.getHeight(), 1);
? ? ? ? Random random =new Random();
? ? ? ? downPosX = random.nextFloat() *(wd -1);
? ? ? ? downPosY = random.nextFloat() *(hg -1);
? ? }
? ? transformedEvent.setLocation(downPosX, downPosY);
? ? Logger.d(TAG, "dispatchChildTouchEvent"+" posx " +downPosX +" posy " +downPosY);
? ? return child.dispatchTouchEvent(transformedEvent);
}