本文为大家分享了Android使用TouchDelegate增加视图触摸范围的方法,供大家参考,具体内容如下
还不知道TouchDelegate这个东西的可以先看一下API,这里大致说一下它的作用:假设有两个观点,分别是v1、v2,我们可以通过v1的setTouchDelegate(边界v2)来委派触摸事件,其中边界是一个Rect.v1中,落在这个范围的TouchEvent都会传给v2。
既然是这样,那我们可以通过设置某个视图的父的touchDelegate来达到扩大这个视图触摸范围的目的。关键是什么时候去执行parent.setTouchDelegate()方法呢?要设置这个委派,必须得知道当前视图大小以及它在父的位置。而这些数据都是在onLayout才能确定(注:如果不是自定义,只是在活动中设置,请将这些操作置于onWindowFocusChanged()方法中)。至此,实现的思路已经很清晰了,我们通过自定义一个按钮来检验一下,下面开始上代码:
为了方便在xml中使用我们自定义的观点,并且可以自定义扩大的触摸范围,我们再自定义一个attrs, res/价值/attrs.xml:
& lt; & # 63; xml version=" 1.0 " encoding=" utf - 8 " & # 63;比; & lt; resources> & lt; declare-styleable name=" LargeTouchableAreaView比; & lt; attr name==拔取?凹臃ā备袷奖? & lt; attr=name=" additionBottom "格式"维度"/比; & lt; attr=name=" additionLeft "格式"维度"/比; & lt; attr=name=" additionRight "格式"维度"/比; & lt; attr=name=" additionTop "格式"维度"/比; & lt;/declare-styleable> & lt;/resources>>之前按钮实现:
公开课LargeTouchableAreasButton扩展按钮{ 私人最终int TOUCH_ADDITION=0; 私人int mTouchAdditionBottom=0; 私人int mTouchAdditionLeft=0; 私人int mTouchAdditionRight=0; 私人int mTouchAdditionTop=0; 私人int mPreviousLeft=1; 私人int mPreviousRight=1; 私人int mPreviousBottom=1; 私人int mPreviousTop=1; 公共LargeTouchableAreasButton(上下文语境){ 超级(上下文); } 公共LargeTouchableAreasButton(上下文语境,AttributeSet attrs) { 超级(上下文,attrs); init(上下文,attrs); } 公共LargeTouchableAreasButton(上下文语境、AttributeSet attrs int defStyle) { 超级(上下文、attrs defStyle); init(上下文,attrs); } 私人空间init(上下文语境,AttributeSet attrs) { TypedArray=context.obtainStyledAttributes (attrs, R.styleable.LargeTouchableAreaView); int除了=(int) a.getDimension ( R.styleable。LargeTouchableAreaView_addition TOUCH_ADDITION); mTouchAdditionBottom=之外; mTouchAdditionLeft=之外; mTouchAdditionRight=之外; mTouchAdditionTop=之外; mTouchAdditionBottom=(int) a.getDimension ( R.styleable.LargeTouchableAreaView_additionBottom, mTouchAdditionBottom); mTouchAdditionLeft=(int) a.getDimension ( R.styleable.LargeTouchableAreaView_additionLeft, mTouchAdditionLeft); mTouchAdditionRight=(int) a.getDimension ( R.styleable.LargeTouchableAreaView_additionRight, mTouchAdditionRight); mTouchAdditionTop=(int) a.getDimension ( R.styleable.LargeTouchableAreaView_additionTop, mTouchAdditionTop); a.recycle (); } @Override 保护空白> xmlns: lta=" http://schemas.android.com/apk/res/com.xxx.xxx "其中“本公司”这个名字可以随便取,最后的是你的程序包名。
最后在这个按钮中定义希望增大的尺寸:& lt; com.xxx.LargeTouchableAreasButton android: layout_width=" wrap_content " android: layout_height=" wrap_content " lta:除了=" 30 dp/比;>之前大功告成。
但这个自定义的观点并不是完美的,还存在以下问题:
1,必须保证父母足够大,如果自定义的范围超出父母的大小,则超出的那部分无效。
2,一个父母只能设置一个触摸委派,设置多个时,只有最后设置的孩子有效。如果希望一个视图能设置多个委派,需要再自定义父母,具体方法可参考:链接地址
总而言之,要触发委派,必须保证父母接收到了触摸事件,并且落在了你定义的范围内。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
Android使用TouchDelegate增加视图的触摸范围