美文网首页
扩大View的点击区域

扩大View的点击区域

作者: 雨来 | 来源:发表于2022-08-09 13:33 被阅读0次

工具类:

public class ViewUtils {
    public static void setTouchDelegate(View view, int expandLeftValue, int expandTopValue, int expandRightValue, int expandBottomValue) {
        View parentView = (View) view.getParent();
        parentView.post(new Runnable() {
            @Override
            public void run() {
                Rect rect = new Rect();
                view.getHitRect(rect); //这个方法后rect里面便有了值
                rect.left -= DpUtils.dip2px(view.getContext(), expandLeftValue);
                rect.top -= DpUtils.dip2px(view.getContext(), expandTopValue);
                rect.right += DpUtils.dip2px(view.getContext(), expandRightValue);
                rect.bottom += DpUtils.dip2px(view.getContext(), expandBottomValue);
                parentView.setTouchDelegate(new TouchDelegate(rect, view)); //委托给parentView
            }
        });
    }
}

一个转换工具类:

public class DpUtils {


    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将px值转换为sp值,保证文字大小不变
     */
    public static int px2sp(Context context, float pxValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值,保证文字大小不变
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


} 

项目中使用:

image.png

参考:
https://www.jianshu.com/p/80da2aec5dbc

相关文章

网友评论

      本文标题:扩大View的点击区域

      本文链接:https://www.haomeiwen.com/subject/wvrnwrtx.html