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

来源:互联网 发布:金融程序员薪资水平 编辑:程序博客网 时间:2024/06/03 16:56

  • 起因
  • 使用TouchDelegate

起因

有时候要求的视图区域很小,但响应区域要求很大。一般解决办法很多,可以用一个透明的布局去回调响应事件,另外也可以采用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