SoFunction
Updated on 2025-04-10

Detailed explanation of the selector effect example of Android ImageView

Detailed explanation of the selector effect example of Android ImageView

In normal development, such as Button, we add selectors to present pressed and normal effects respectively, which greatly enhances our user experience. However, when we use ImageView to "tend" one by one, we find that setting the selector directly does not work. Of course, our application will behave at this time. Then we can only find a way to solve this situation.

First define a selector file:

<selector xmlns:andro >
  <item android:state_pressed="true">
    <shape android:shape="rectangle">
      <corners android:radius="5dp" />
      <solid android:color="#50000000"/>
    </shape>
  </item>

  <item >
    <shape android:shape="rectangle">
      <corners android:radius="5dp" />
      <solid android:color="#00000000"/>
    </shape>
  </item>

</selector>

The second step is to set the selector for the src of the ImageView.

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:contentDescription="@null"
    android:scaleType="centerCrop"
    android:src="@drawable/share_image_selector" />

Then the image resources to be presented on our ImageVIew are used

();

In other words, we set the backgroundResource for the imageview, and then set the selector we set for src. Visually, our selector is displayed above the ImageView. Of course, when we click on the ImageView, the selector will be triggered, and at this time there will be a pressing effect.

The above is the custom development of Android ImageView. Many things need to be rewritten for Android. If you are not beautiful, it is definitely not a good app. There are many articles on Android development on this site. Please refer to it. Thank you for your support for this site!