1.Android提供TouchDelegate幫助實現擴大一個很小的view的點擊區域
例如:https://developer.android.com/training/gestures/viewgroup.html#delegate
布局文件
<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" tools:context=".MainActivity" >
<ImageButton android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@null" android:src="@drawable/icon" />
</RelativeLayout>
代碼
// 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); } } });
簡單解釋
1. 獲取parentView並且在UIThread上post一個Runnable,確保viewGroup在繪制子view之前得到子view的getHintRect(),getHintRect()返回就是該view在viewGroup中的點擊區域
2.Find這個View,並且通過getHintRect()得到點擊區域,rect
3.擴大點擊范圍即擴大rect的left,right,top,bottom
4.初始化TouchDelegate,並且將擴大后的rect和view對象作為參數傳入
5.在viewGroup中設置touchDelegate,viewGroup會自動擴大該view的響應區域
