在应用经常会遇到按钮比较小,点击时有时无法响应事件,又不能将控件增大的时候,这时我们可以用TouchDelegate来增大按钮的响应area
code:
private void accretionArea() {
View parent = (View) mButton.getParent();
// <p>This method can be invoked from outside of the UI thread only when
// this View is attached to a window.</p>
parent.post(new Runnable() {
public void run() {
Rect outRect = new Rect();
// 只有在parent is attached to a window 时这个outRect为mButton
// 否则坐标都为0,这也是为什么要在post里执行的原因。
// 后的按钮的区域坐标--outRect;
mButton.getHitRect(outRect);
Log.d("lhz", "区域范围" + outRect.left + "---" + outRect.bottom);
outRect.left -= 200;
outRect.top -= 200;
outRect.right += 200;
outRect.bottom += 200;
// 传入一个区域和view 这个区域将代理这个view
TouchDelegate deldgate = new TouchDelegate(outRect, mButton);
// 判断类似与 instanceof
if (View.class.isInstance(mButton.getParent())) {
((View) mButton.getParent()).setTouchDelegate(deldgate);
Log.e("lhz", "设置了代理");
}
}
});
}