Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add bigger transparent overlay to increase clickable area, without changing layout

I want to increase the clickable area of my button (ImageView). But I don't want this to be reflected visually. It has to look like the button is small (no margin, padding, etc.) but the clickable area is big.

enter image description here

The only thing I can think about is put my whole layout in a RelativeLayout and add the overlays programmatically to a second "layer". Calculate margin left and margin top with maths.

Is there a better approach?

I already looked here Expand clickable area of an ImageView by using padding?

or here Making a button easier to click

And some others but they always change the layout adding padding or transparent areas to the image, I don't want to do that.

like image 516
User Avatar asked Oct 07 '22 12:10

User


1 Answers

Use a TouchDelegate, as outlined in this blog post.

The gist is that you can define a TouchDelegate object and attach it to a widget to increase its touch area, without having a visual impact.

In Kotlin, this might look like:

    fun setExpandedTouchArea(view: View, extraSpace: Int) {
        val parent = view.parent as View

        parent.doOnLayout {
            val area = Rect()

            view.getHitRect(area)

            area.top -= extraSpace
            area.bottom += extraSpace
            area.left -= extraSpace
            area.right += extraSpace

            parent.touchDelegate = TouchDelegate(area, view)
        }
    }
like image 171
CommonsWare Avatar answered Oct 12 '22 10:10

CommonsWare