Java 如何在android上为按下和释放按钮定制?
我知道这里有很多这样的问题,但我真的不知道我的代码不起作用的原因。 我试着制作一个有三种状态的按钮:正常、按下和释放。当我说release时,我的意思是我想把它做成一个toogle按钮,状态为Java 如何在android上为按下和释放按钮定制?,java,android,button,Java,Android,Button,我知道这里有很多这样的问题,但我真的不知道我的代码不起作用的原因。 我试着制作一个有三种状态的按钮:正常、按下和释放。当我说release时,我的意思是我想把它做成一个toogle按钮,状态为活动和非活动 当我松开按钮时,它将返回默认状态。我想通过单击更改图像,因为选中按钮起作用 我试过这个: 自定义按钮m.xml: <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schema
活动
和非活动
当我松开按钮时,它将返回默认状态。我想通过单击更改图像,因为选中按钮起作用
我试过这个:
自定义按钮m.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/focussed" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/focussedandpressed" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/pressed" />
<item android:drawable="@drawable/default" />
</selector>
layout.xml:
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/menu"
android:layout_weight="1" android:background="@drawable/custom_button"></Button>
您使用的是
android:state\u focused
和android:state\u pressed
那怎么办?你想要像Checkbox这样的定制功能,对吗?在这种情况下,需要两个图像用于状态检查true和false,以及一个透明的背景文件(没有内容,只是与其他图像大小相同)。创建两个可绘制选择器文件,其内容如下: background\u selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/your_bg" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/checkbox_on" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/checkbox_off" />
<item android:state_checked="false"
android:drawable="@drawable/checkbox_off" />
<item android:state_checked="true"
android:drawable="@drawable/checkbox_on" />
</selector>
state\u selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/your_bg" />
</selector>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/checkbox_on" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/checkbox_off" />
<item android:state_checked="false"
android:drawable="@drawable/checkbox_off" />
<item android:state_checked="true"
android:drawable="@drawable/checkbox_on" />
</selector>
将这些xml放入可绘制文件夹,并在布局中创建一个复选框:
<CheckBox
android:layout_width="50dip"
android:layout_height="50dip"
android:background="@drawable/background_selector"
android:button="@drawable/state_selector"
/>
希望这有帮助^ ^我试过这个: