在做一个一个页面,发现有些小Button实在是很难击中,可能你会想各种办法,比如在外面套一个大的容器、把Padding设置的大一点等等,今天给你提供一个新思路。
扩大view的点击区域
今天在看View代码时,发现有个方法叫setTouchDelegate
,后来查阅了一下发现这个实际上是个代理类,我们可以通过它的父组件来扩大点击区域。
代码很简单,直接贴上吧:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
|
public static void expandViewTouchDelegate(final View view, final int top, final int bottom, final int left, final int right) {
((View) view.getParent()).post(new Runnable() { @Override public void run() { Rect bounds = new Rect(); view.setEnabled(true); view.getHitRect(bounds);
bounds.top -= top; bounds.bottom += bottom; bounds.left -= left; bounds.right += right;
TouchDelegate touchDelegate = new TouchDelegate(bounds, view);
if (View.class.isInstance(view.getParent())) { ((View) view.getParent()).setTouchDelegate(touchDelegate); } } }); }
public static void restoreViewTouchDelegate(final View view) {
((View) view.getParent()).post(new Runnable() { @Override public void run() { Rect bounds = new Rect(); bounds.setEmpty(); TouchDelegate touchDelegate = new TouchDelegate(bounds, view);
if (View.class.isInstance(view.getParent())) { ((View) view.getParent()).setTouchDelegate(touchDelegate); } } }); }
|