如何使用选择器更改ImageButton图像? [英] How to use a selector to change an ImageButton image?
问题描述
如何在按下ImageButton图像时更改其图像?
How do I make an ImageButton image change its image when you press it?
推荐答案
希望您对此有帮助.
这一切都可以在XML中完成.
This can all be done in the XML.
1)将处于按下状态和未按下状态的图像导入res/drawable- 任何一个文件夹
1) Import your images for both pressed and unpressed states into the res/drawable-whichever folder
2)选择您的选择器.右键单击可绘制文件夹,然后选择新建/Android xml文件".输入名称,例如"ok_button_selector.xml",然后从下面的菜单中选择选择器"作为根元素. 您将需要为屏幕上的每个按钮创建一个不同的选择器.
2) Make your selectors. Right click on a drawable folder and select New/Android xml file. Put in the name eg "ok_button_selector.xml" and choose "selector" as the root element from the menu below. You will need to create a different selector for each button on the screen.
3)在每个选择器文件中,您需要定义单击时将显示的图像,如下所示:
3) In each selector file you need to define the image that will display when clicked, like this:
<!-- language: lang-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/search_icon_pressed"/>
<item
android:drawable="@drawable/search_icon"/>
</selector>
它们必须按此顺序排列,因为默认是最后一个.
They have to be in this order as the last is the default.
4)在布局文件中,使用android:onClick ="myButtonClicked"方法定义按钮的单击行为.这省去了使用点击监听器的麻烦.只要确保您的java方法具有相同的名称即可:-)
4) In your layout file use the android:onClick="myButtonClicked" method to define the buttons clicked behaviour. This saves having to use click listeners. Just make sure your java method has the same name :-)
5)在ImageButton标记中,定义属性android:src ="@ drawable/ok_button_selector"而不是普通的图像文件.
5) Within the ImageButton tags define the attribute android:src="@drawable/ok_button_selector" instead of the usual image file.
就是这样!您的java onClick方法中不需要任何额外的代码.
Thats it! You don't need any extra code in your java onClick method.
这篇关于如何使用选择器更改ImageButton图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!