androidfocusimageviewclickablefocusable

Android layout - ImageView focused, but doesn't show anything on screen (no highlight)


If I set my ImageView to be both clickable and focusable, it works, but I have no way to tell which image is focused. What's the best way to get it to draw an orange border around the view so the user knows it's currently in focus?

I tried dropping it in a LinearLayout and setting that to be focusable and clickable instead, but didn't have any luck. Even when I put a margin on it, there's nothing to indicate that it was selected.


Solution

  • You can use a drawable with a selector as the background.

    For example, I have gallery_image_bg.xml in res/drawable:

    <?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android"
              android:constantSize="true">
      <item android:state_selected="true">
        <shape android:shape="rectangle">
          <solid android:color="#E6E4E0"/>
          <stroke android:width="3dp" android:color="#F9C11E"/>
          <padding android:left="3dp"
                   android:top="3dp"
                   android:right="3dp"
                   android:bottom="3dp" />
        </shape>
      </item>
      <item android:state_pressed="true">
        <shape android:shape="rectangle">
          <solid android:color="#E6E4E0"/>
          <stroke android:width="3dp" android:color="#F9C11E"/>
          <padding android:left="3dp"
                   android:top="3dp"
                   android:right="3dp"
                   android:bottom="3dp" />
        </shape>
      </item>
      <item>
        <shape android:shape="rectangle">
          <solid android:color="#E6E4E0"/>
          <stroke android:width="3dp" android:color="#FFF"/>
          <padding android:left="3dp"
                   android:top="3dp"
                   android:right="3dp"
                   android:bottom="3dp" />
        </shape>
      </item>
    </selector>
    

    This creates three different-colored 3dp lines around the image. They are visible because the padding forces the image to render in a slightly smaller area.

    Used in code like so:

    image.setBackgroundResource(R.drawable.gallery_image_bg)