使用TouchDelegate扩大View的点击区域

来源:互联网 发布:虚拟主机 阿里云 编辑:程序博客网 时间:2024/04/28 01:41

TouchDelegate可以增大view的可点击区域。当view较小时,TouchDelegate就派上用场了。

TouchDelegate使用非常简单,只需要几行代码:

private static class TouchDelegateLayout extends FrameLayout {private CheckBox checkBox;public TouchDelegateLayout(Context context, AttributeSet attrs, int defStyle) {super(context, attrs, defStyle);init();}public TouchDelegateLayout(Context context, AttributeSet attrs) {super(context, attrs);init();}public TouchDelegateLayout(Context context) {super(context);init();}private void init() {checkBox = new CheckBox(getContext());FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);params.gravity = Gravity.CENTER;addView(checkBox, params);
<span style="white-space:pre"></span>/* 使用post runnable的方式去设置Delegate区域大小的原因是,如该View师在Activity的OnCreate()或Fragment的OnCreateView()中绘制,此时UI界面尚未开始绘制,无法获得正确的坐标; */post(new Runnable() {@Overridepublic void run() {Rect bound = new Rect();TouchDelegateLayout.this.getHitRect(bound);TouchDelegate delegate = new TouchDelegate(bound, checkBox);TouchDelegateLayout.this.setTouchDelegate(delegate);}});}}


0 0
原创粉丝点击