/** * Adds a touchable padding around a View by constructing a TouchDelegate * and adding it to parent View. * @param parent The "outer" parent View * @param delegate The delegate that handles the TouchEvents * @param topPadding Additional touch area in pixels above View * @param bootomPadding Additional touch area in pixels below View * @param topPadding Additional touch area in pixels left to View * @param topPadding Additional touch area in pixels right to View * @return A runnable that you can post as action to a Views event queue */privatestatic Runnable getTouchDelegateAction(final View parent,final View delegate,finalint topPadding,finalint bottomPadding,finalint leftPadding,finalint rightPadding){returnnewRunnable(){@Overridepublicvoidrun(){//Construct a new Rectangle and let the Delegate set its values
Rect touchRect =new Rect();
delegate.getHitRect(touchRect);//Modify the dimensions of the Rectangle//Padding values below zero are replaced by zeros
touchRect.top-=Math.max(0, topPadding);
touchRect.bottom+=Math.max(0, bottomPadding);
touchRect.left-=Math.max(0, leftPadding);
touchRect.right+=Math.max(0, rightPadding);//Now we are going to construct the TouchDelegate
TouchDelegate touchDelegate =new TouchDelegate(touchRect, delegate);//And set it on the parent
parent.setTouchDelegate(touchDelegate);}

使用方法:

1
2
3
4
5
6

//Get references to the View in the layout
parent =(View) findViewById(R.id.parent);
delegateButton =(View) findViewById(R.id.cmdClickMe);//The TouchDelegate has to be set after everything has been calculated and drawn
parent.post(getTouchDelegateAction(parent, delegateButton,50,50,50,50));