使用TouchDelegate扩大View的点击区域

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() {

			@Override
			public void run() {
				Rect bound = new Rect();
				TouchDelegateLayout.this.getHitRect(bound);
				TouchDelegate delegate = new TouchDelegate(bound, checkBox);
				TouchDelegateLayout.this.setTouchDelegate(delegate);
			}
		});
	}
}


你可能感兴趣的:(android,delegate)