我有两个电源按钮图像,一个是红色,另一个是绿色。我想创建一个按钮,最初将其背景资源设置为红色电源按钮。我希望它的资源在按下时更改为绿色,再次单击后,我希望它再次变回红色。请帮忙...
最佳答案
这样做:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/check" //check.xml
android:layout_margin="10dp"
android:textOn=""
android:textOff=""
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_centerVertical="true"/>
在drawable文件夹中创建check.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
这工作得很好。
关于java - 如何改变图片按钮的背景资源来实现开关机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15675458/