Android 按下时将按钮背景从透明更改为彩色
我的应用程序中有一些背景透明的按钮。现在,我想定制它们以保持透明的背景,但是当按下它们时,背景应该变成绿色 我知道这里有很多关于自定义按钮的主题,所以我已经阅读了其中的一些,还有很多来自谷歌的教程。虽然这看起来很容易,但我并没有让它发挥作用 这是我的按钮的示例代码:Android 按下时将按钮背景从透明更改为彩色,android,Android,我的应用程序中有一些背景透明的按钮。现在,我想定制它们以保持透明的背景,但是当按下它们时,背景应该变成绿色 我知道这里有很多关于自定义按钮的主题,所以我已经阅读了其中的一些,还有很多来自谷歌的教程。虽然这看起来很容易,但我并没有让它发挥作用 这是我的按钮的示例代码: <Button android:id="@+id/accept_button" android:layout_width="wrap_content" android:layout_height="wr
<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" />
此文件位于res/drawable文件夹中
在我的应用程序中,按钮可以正确地获得默认的透明背景,但在聚焦或按下时,背景颜色不会变为绿色。试试看,这可能会对您有所帮助
<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>
使用选择器
<?xml version="1.0" encoding="utf-8"?>
然后
<Button
android:id="@+id/button1"
android:background="@drawable/Selector File Name"
android:layout_width="200dp"
android:layout_height="126dp"
android:text="Hello" />
我不知道为什么,但我尝试过类似的方法,但没有成功。。。但现在它正在发挥作用。干得好
<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" />