Search code examples
androidandroid-imageviewandroid-relativelayout

Increasing clickable area of ImageView


I have created a RelativeLayout shown below as part of a toolbar. The layout consists of two images and a thin line below the images. For the two images I have increased the width because then the clickable area is wider. A screenshot (Android Studio) how it looks like is shown at the bottom.

The problem now is that I can't control the size of the image (the image is just placed in the center). How can I fix the actual size of the image to 25 x 25 dp and still extend the clickable area to the left and right of the image by let's say 70 dp and at the bottom and top of the image by 10 dp?

<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard_toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="horizontal">

    <View
        android:id="@+id/keyboard_toolbar_line"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_below="@id/privacyButton"
        android:layout_marginBottom="5dp"
        android:background="#c0c0c0"/>

    <ImageView
        android:id="@+id/privacyButton"
        android:layout_width="100dp"
        android:layout_alignParentStart="true"
        android:layout_height="35dp"
        android:scaleType="center"
        android:layout_marginStart="30dp"
        android:src="@drawable/research_ic_lock_open_dark" />

    <ImageView
        android:id="@+id/ratingButton"
        android:layout_width="100dp"
        android:layout_alignParentEnd="true"
        android:layout_height="35dp"
        android:scaleType="center"
        android:layout_marginEnd="30dp"
        android:src="@drawable/ic_star" />

</RelativeLayout >

enter image description here


Solution

  • You may think of wrapping it in a LinearLayout that has the exact extra width & height you want, and keep your image in 25x25dp; then add the click listener to the LinearLayout instead of the ImageView

    sample for one image:

    <LinearLayout
        android:layout_width="140dp"
        android:gravity="center"
        android:layout_height="35dp">
    
        <ImageView
            android:id="@+id/privacyButton"
            android:layout_width="25dp"
            android:layout_height="25dp"
            android:layout_alignParentStart="true"
            android:layout_marginStart="30dp"
            android:scaleType="center"
            android:src="@drawable/quarter_circle" />
    
    </LinearLayout>
    

    I just added arbitrary values for the LinearLayout, for the width, as you need 70dp to the right and left so the total is 140.