代码增大响应区域
- Gets the parent view and posts a
Runnable
on the UI thread. This ensures that the parent lays out its children before calling thegetHitRect()
method. ThegetHitRect()
method gets the child's hit rectangle (touchable area) in the parent's coordinates. - Finds the
ImageButton
child view and callsgetHitRect()
to get the bounds of the child's touchable area. - Extends the bounds of the
ImageButton
's hit rectangle. - Instantiates a
TouchDelegate
, passing in the expanded hit rectangle and theImageButton
child view as parameters. - Sets the
TouchDelegate
on the parent view, such that touches within the touch delegate bounds are routed to the child.
ImageButton
child view, the parent view will receive all touch events. If the touch event occurred within the child's hit rectangle, the parent will pass the touch event to the child for handling.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the parent view
View parentView = findViewById(R.id.parent_layout);
parentView.post(new Runnable() {
// Post in the parent's message queue to make sure the parent
// lays out its children before you call getHitRect()
@Override
public void run() {
// The bounds for the delegate view (an ImageButton
// in this example)
Rect delegateArea = new Rect();
ImageButton myButton = (ImageButton) findViewById(R.id.button);
myButton.setEnabled(true);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this,
"Touch occurred within ImageButton touch region.",
Toast.LENGTH_SHORT).show();
}
});
// The hit rectangle for the ImageButton
myButton.getHitRect(delegateArea);
// Extend the touch area of the ImageButton beyond its bounds
// on the right and bottom.
delegateArea.right += 100;
delegateArea.bottom += 100;
// Instantiate a TouchDelegate.
// "delegateArea" is the bounds in local coordinates of
// the containing view to be mapped to the delegate view.
// "myButton" is the child view that should receive motion
// events.
TouchDelegate touchDelegate = new TouchDelegate(delegateArea,
myButton);
// Sets the TouchDelegate on the parent view, such that touches
// within the touch delegate bounds are routed to the child.
if (View.class.isInstance(myButton.getParent())) {
((View) myButton.getParent()).setTouchDelegate(touchDelegate);
}
}
});
}
}