- Parameters:
- bounds Bounds in local coordinates of the containing view that should be mapped to the delegate view
- delegateView The view that should receive motion events
public class TouchDelegateActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.touch_delegate); View parentView = findViewById(R.id.parent_layout); parentView.post(new Runnable() { @Override public void run() { 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(TouchDelegateActivity.this,"click",Toast.LENGTH_SHORT).show(); } }); myButton.getHitRect(delegateArea); // 在ImageButton边框的右边和底边扩展触摸区域 delegateArea.right += 200; delegateArea.bottom += 200; 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); } } }); } }
2.布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/parent_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageButton android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:src="@drawable/icon" /> </RelativeLayout>