android 觸摸委托擴展view的觸摸面積

"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>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容