我想在按下时改变按钮的颜色,但是对于它我已经有了
android:background="@drawable/shape_layout"
shape_layout.xml代码:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#ff055500"
android:endColor="#ff055500"/>
<corners android:radius="1dp" />
<stroke android:width="1px" android:color="#ffffff" />
</shape>
那么按下时如何改变按钮的颜色?
答案 0 :(得分:3)
您需要创建一个selector-drawable:
<强> shape_selector.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/shape_layout_pressed"/>
<item android:state_focused="true" android:drawable="@drawable/shape_layout_focused"/>
<item android:drawable="@drawable/shape_layout"/>
</selector>
将所需的按下/聚焦状态颜色添加到新的XML-drawables,并将selector-drawable设置为背景:
android:background="@drawable/shape_selector"
答案 1 :(得分:2)
您还需要两个XML文件:
选择器XML的示例:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@drawable/shape_layout_hover" />
<item android:state_focused="true" android:drawable="@drawable/shape_layout_hover" />
<item android:drawable="@drawable/shape_layout" />
</selector>
然后创建按钮样式,选择器文件作为背景。并将该样式设置为按钮项。
<item name="android:background">@drawable/button_selector</item>