1. 程式人生 > >工具類:點選擴大點選區域的

工具類:點選擴大點選區域的

package com.sikkha.skline.utils;

import android.graphics.Rect;
import android.view.TouchDelegate;
import android.view.View;

/**
 * ================================================
 *
 * @author:Vip 版    本:V 5.0.0
 * 建立日期:2018/8/29
 * 描    述:點選擴大點選區域的工具類
 * 修訂歷史:
 * ================================================
 */
public class TouchDelegateUtils {
    /**
     * 增加控制元件的可點選範圍,最大範圍只能是父佈局所包含的的區域
     */
    public static void addDefaultScreenArea(final View view, final int top, final int bottom, final int left, final int right) { // 增大checkBox的可點選範圍
        final View parent = (View) view.getParent();
        parent.post(new Runnable() {
            @Override
            public void run() {
                Rect bounds = new Rect();
                view.setEnabled(true);
                view.getHitRect(bounds);

                bounds.top -= top;
                bounds.bottom += bottom;
                bounds.left -= left;
                bounds.right += right;

                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                if (View.class.isInstance(view.getParent())) {
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });

    }

    /**
     * 還原View的觸控和點選響應範圍,最小不小於View自身範圍
     *
     * @param view
     */
    public static void restoreViewTouchDelegate(final View view) {

        ((View) view.getParent()).post(new Runnable() {
            @Override
            public void run() {
                Rect bounds = new Rect();
                bounds.setEmpty();
                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                if (View.class.isInstance(view.getParent())) {
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });

    }
}