Is there an example of how to use a TouchDelegate in Android to increase the size of a view's click target?

后端 未结 11 609
误落风尘
误落风尘 2020-11-28 19:01

My understanding is that when you have a view that\'s too small to easily touch, you\'re supposed to use a TouchDelegate to increase the clickable region for that view.

11条回答
  •  余生分开走
    2020-11-28 19:18

    I was able to accomplish this with multiple views (checkboxes) on one screen drawing largely from this blog post. Basically you take emmby's solution and apply it to each button and its parent individually.

    public static void expandTouchArea(final View bigView, final View smallView, final int extraPadding) {
        bigView.post(new Runnable() {
            @Override
            public void run() {
                Rect rect = new Rect();
                smallView.getHitRect(rect);
                rect.top -= extraPadding;
                rect.left -= extraPadding;
                rect.right += extraPadding;
                rect.bottom += extraPadding;
                bigView.setTouchDelegate(new TouchDelegate(rect, smallView));
            }
       });
    }
    

    In my case I had a gridview of imageviews with checkboxes overlaid on top, and called the method as follows:

    CheckBox mCheckBox = (CheckBox) convertView.findViewById(R.id.checkBox1);
    final ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView1);
    
    // Increase checkbox clickable area
    expandTouchArea(imageView, mCheckBox, 100);
    

    Working great for me.

提交回复
热议问题