"Little things make big things happen." – John Wooden
TouchDelegate 觸摸委派,android提供了這么一個精巧的類,實在讓人喜愛。當我們需要放大或縮小一個view的觸摸區域時,可以用到它。
注意:
1:不能放大到這個view的父控件之外去。不然父控件之外的區域就無效了。
2:一個父控件只能設置一個觸摸委派到子view上,設置多個的話,最后一個設置生效。
代碼和布局如下,很簡單,就不需要多講解了。
public class Main3Activity extends Activity {
private LinearLayout ll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
ll= (LinearLayout) findViewById(R.id.ll);
ll.post(new Runnable() {
@Override
public void run() {
Button button = (Button) findViewById(R.id.button);
Rect rect=new Rect();
//獲取button的觸摸區域,傳入一個空的矩形對象,該方法會對空的矩形對象進行賦值
button.getHitRect(rect);
rect.right+=200;
rect.bottom+=200;
// 創建TouchDelegate 對象,觸摸矩形區域,和view
TouchDelegate touchDelegate=new TouchDelegate(rect,button);
// 通過父布局設置view的觸摸委托
ll.setTouchDelegate(touchDelegate);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("--->","test");
}
});
}
});
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:text="button"
android:id="@+id/button"
android:layout_gravity="center"
android:layout_width="40dp"
android:layout_height="40dp" />
</LinearLayout>