如何使图像视图的选择器仅更改背景而不更改图像源?

2024-04-19

我有一个 ImageView,同时设置了图像 src 和背景颜色。

该图像位于 gridview 项目布局的布局中。

我想创建一个 xml 选择器,当选择该项目时,图像背景会改变,但图像 src 不会改变。

类似于带有文本图标的android主菜单,我只想突出显示图像。

我不会为对象的每种状态制作图像,我只想更改背景。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/img_0"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:background="@drawable/selector_categorie"
        android:src="@drawable/ic_launcher"/>

    <TextView
        android:id="@+id/text_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/img_0"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/text_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_1"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/text_3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_2"
        android:layout_marginTop="15dp"
        android:gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium" />


</RelativeLayout>

这可以通过以下方式实现可绘制状态列表 http://developer.android.com/reference/android/graphics/drawable/StateListDrawable.html.

创建一个背景可绘制资源,例如item_background.xml, 在你的/drawable文件夹,包含这样的内容:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@color/color1" android:state_pressed="true"/>
  <item android:drawable="@color/color2" android:state_selected="true"/>
  <item android:drawable="@color/color3" android:state_activated="true"/>
  <item android:drawable="@color/color4"/>
</selector>

然后提供您的颜色值/values/colors.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="color1">#DDff8800</color>
  <color name="color2">...</color>
  <!-- more colors... -->
</resources>

最后,将该可绘制资源设置为布局中的项目背景android:background="@drawable/item_background".

The src图像保持不变。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使图像视图的选择器仅更改背景而不更改图像源? 的相关文章

随机推荐