我的应用中有一些透明背景的按钮。现在,我想自定义它们以保持透明背景,但是当按下它们时,背景应该变为绿色。
我知道这里有很多关于自定义按钮的主题,我已经介绍了其中几个,也有很多来自谷歌的教程。虽然这似乎是一件容易的事,但我并没有让它发挥作用。
这是我的按钮的示例代码:
<Button
android:id="@+id/accept_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:background="@drawable/button_state"
android:text="@string/btnaccept"
android:textStyle="bold" />
这是选择器xml文件buton_state.xml
,我已经为不同的按钮状态定义了背景颜色变化:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Button focused and pressed-->
<item android:state_pressed="true"
android:state_focused="true" >
<shape>
<solid
android:color="@color/LightGreen" />
</shape>
</item>
<!-- Button Default-->
<item android:state_pressed="false"
android:state_focused="false" >
<shape>
<solid
android:color="@android:color/transparent" />
</shape>
</item>
</selector>
此文件位于res / drawable文件夹中。
在我的应用程序中,按钮正确显示默认的透明背景,但在聚焦或按下时,此背景颜色不会变为绿色。
答案 0 :(得分:2)
试试这可能对你有帮助,
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:drawable="@color/LightGreen" /> <!--pressed -->
<item android:drawable="@android:color/transparent" /> <!-- Normal -->
</selector>
答案 1 :(得分:0)
使用选择器
<?xml version="1.0" encoding="utf-8"?>
<item android:drawable="@drawable/numpad_button_bg_selected" android:state_selected="true"></item>
<item android:drawable="@drawable/numpad_button_bg_pressed" android:state_pressed="true"></item>
<item android:drawable="@drawable/numpad_button_bg_normal"></item>
然后
<Button
android:id="@+id/button1"
android:background="@drawable/Selector File Name"
android:layout_width="200dp"
android:layout_height="126dp"
android:text="Hello" />