问题
I have an ImageView with both image src and background color set.
This image is into a layout that is the gridview item layout.
I would to create an xml selector that when the item is choosen, the image background change, but the image src not.
Something similar to the main menu of android with icon with text, I want to highlight only the image.
I would not to make an image for each state of the object, I only want to change the background.
<?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>
回答1:
This can be achieved with a StateListDrawable.
Create a background drawable resource, e.g. item_background.xml, in your /drawable folder, containing something like this:
<?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>
Then provide the color values in your /values/colors.xml file:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="color1">#DDff8800</color>
<color name="color2">...</color>
<!-- more colors... -->
</resources>
Finally, set that drawable resource as the item background in your layout with android:background="@drawable/item_background".
The src image remains untouched.
来源:https://stackoverflow.com/questions/14302940/how-can-i-make-selector-for-an-imageview-to-change-only-the-background-but-not-t