Android 解决视图小而触发事件区域大的办法

起因

有时候要求的视图区域很小,但响应区域要求很大。一般解决办法很多,可以用一个透明的布局去回调响应事件,另外也可以采用Deletgate(代理事件),就是把响应区域的事件直接传递到指定的应该响应的view.

使用TouchDelegate

这个解决办法可以指定区域响应,若继承一个ViewGroup应该在onSizeChanged()中去实现。代码如下:

    /*
     * TouchDelegate is applied to this view (parent) to delegate all touches
     * within the specified rectangle to the CheckBox (child). Here, the
     * rectangle is the entire size of this parent view.
     * 
     * This must be done after the view has a size so we know how big to make
     * the Rect, thus we've chosen to add the delegate in onSizeChanged()
     */
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        if (w != oldw || h != oldh) {
            // Apply the whole area of this view as the delegate area
            Rect bounds = new Rect(0, 0, w, h);
            TouchDelegate delegate = new TouchDelegate(bounds, mButton);
            setTouchDelegate(delegate);
        }
    }

解决的办法非常简单,但也有一个缺点:

each event forwarded to the
delegate first has its location reset to the exact midpoint of the delegate view. This means that if you attempt
to forward a series of ACTION_MOVE events through TouchDelegate, the results won’t be what you expect,
because they will look to the delegate view as if the finger isn’t really moving at all.

也就是说只会传递一个这个代理view的中心点,滑动事件变化的坐标并不会真实的那样传递。也就是说传递过去的坐标不动的,就是这个view的中心坐标位置。当然这个时候可以通过将坐标传到onTouchEvent(),或者dispatchTouchEvent(event);来解决。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值