Android如何实现ImageView的selector效果

这篇文章给大家分享的是有关Android如何实现ImageView的selector效果的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

Android ImageView的selector效果实例详解

在平时开发中如Button我们给它加上selector分别呈现pressed以及normal效果能给我们的用户体验上大大增色不少,可是我们当我们是用ImageView来”当作”一个一个”Button”的时候发现直接设置selector却不起作用,当然此时我们的应用就表现的暗淡了。那我们就只能找到方法来解决这种情况。

首先定义一个selector文件:

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
  <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>

第二步,给ImageView的src设置该selector。

<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" />

然后我们的ImageVIew上要呈现的图片资源就是用

mImageView.setBackgroundResource(R.drawable.icon);

也就是说我们是给imageview设置backgroundResource,然后给src设置我们设置好的selector,在视觉上我们的selector是显示在ImageView的上方,当然我们点击ImageView的时候就是触发selector,这个时候就会有按下的效果了。

感谢各位的阅读!关于“Android如何实现ImageView的selector效果”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!