Expand clickable area of an ImageView by using padding?

后端 未结 4 841
小蘑菇
小蘑菇 2021-02-04 02:19

I have an ImageView, and I want it to be clickable. The image itself is only 32x32 pixels, but I want the clickable region to be larger so it\'s easier to hit. I was hoping I co

相关标签:
4条回答
  • 2021-02-04 02:39

    Use padding. layout margins are used if for inserting space outside the boundary of the view.

    for equal padding on all sides

      <ImageView
           android:padding="20dip" />
    

    or to set the padding on each side

    <ImageView
         android:paddingLeft="10dip"
         android:paddingRight="15dip"
         android:paddingTop="23dip"
         android:paddingBottom="12dip" />
    

    Hope that helps !

    0 讨论(0)
  • 2021-02-04 02:39

    Instead of resizing the image (Peter Knego's answer) or increasing padding (Saimon's answer) I suggest to set the minWidth and minHeight attributes in combination with scaleType="center":

    <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:minWidth="40dp"
      android:minHeight="40dp"
      android:scaleType="center"
      android:src="@drawable/your_image" />
    

    That makes sure that small images have at least a size of 40x40dp while the image is not up-scaled if it's smaller. If one day the image is going to be replaced with another image larger than minWidth and minHeight it will not grow larger than 40x40dp as it gets downscaled. Thus a minimum clickable dimension of 40x40dp is always guaranted and the image is always displayed nicely.

    0 讨论(0)
  • 2021-02-04 02:41

    Suggestions (never tried it myself):

    1. Create ImageView as large as you want than put image into it without scaling

      ImageView.setScaleType(ImageView.ScaleType.CENTER).
      
    2. Brute force approach: create new larger png that has original image centered and the rest of it is transparent.

    0 讨论(0)
  • 2021-02-04 02:46

    Use like below; where width/height is your touch radius

    <ImageView
      android:id="@+id/editProfile"
      android:layout_width="32dp"
      android:layout_height="32dp"
      android:padding="8dp"
      android:background="?attr/selectableItemBackgroundBorderless"
      android:src="@drawable/ic_edit"
      android:scaleType="fitCenter"
    />
    

    In the above code, I wanted my src size to be viewed as 24dp width/height. And touch radius of 32dp. so I had used padding of 8dp.

    0 讨论(0)
提交回复
热议问题