我想在点击它时更改ImageButton
的背景颜色。所以我要创建选择器......
button_click.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_normal" />
<item android:drawable="@drawable/button_pressed" android:state_pressed="true" />
</selector>
对于这个选择器,我创建了两个drawable: button_normal.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="@color/white_transparent" />
<corners android:radius="2dp" />
<stroke android:color="@color/shadow" android:width="1dp" />
</shape>
</item>
</selector>
和button_pressed.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="#FFCC00" />
<corners android:radius="2dp" />
<stroke android:color="@color/shadow" android:width="1dp" />
</shape>
</item>
</selector>
一切都是一样的,只有我改变颜色。这是我的colors.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="white">#FFFFFF</color>
<color name="black">#000000</color>
<color name="gray">#EEEEEE</color>
<color name="primaryColor">#2196F3</color>
<color name="primaryColorDark">#1976D2</color>
<color name="accentColor">#009688</color>
<color name="shadow">#1A000000</color>
<color name="text_color">#B6B7B9</color>
<color name="button_clicked">#80000000</color>
<color name="white_transparent">#BFFFFFFF</color>
</resources>
我在ImageButton
的main_screen.xml文件中使用此选择器:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_click"
android:padding="@dimen/activity_vertical_margin"
android:clickable="true"
android:id="@+id/btnSinoLoc"
android:src="@drawable/find_sino"
android:layout_margin="@dimen/activity_horizontal_margin"
android:contentDescription="@null"
android:maxHeight="40dp"
android:maxWidth="40dp"
android:adjustViewBounds="true"
android:layout_alignTop="@+id/map"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
但是这不起作用......我按照自己的意愿得到了ImageButton
,但是当我按下时,颜色没有变化。那么我错过了什么,或者还有其他方法可以做到这一点?
答案 0 :(得分:3)
您还必须为statePressed false定义项目:
<item android:drawable="@drawable/button_normal" android:state_pressed="false" />
并设置Your ImageButton的src:
android:src="@drawable/button_click"
您描述了选择器xml的名称为button_click.xml,因此您必须在src属性中调用它。此外,drawables必须是真正的drawables而不是两个选择器。所以你可以塑造一个形状......
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#FFCC00" />
<corners android:radius="2dp" />
<stroke android:color="@color/shadow" android:width="1dp" />
</shape>