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);
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

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

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);来解决。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇