官网介绍:链接
ImageButton继承于ImageView。
ImageButton跟Button不一样,它用图片取代文字。
它默认看起来就像一个能够在不同状态(点击、按住、松开等等)改变颜色的普通Button。
ImageButton上的图像,可以通过android:src这个XML属性,
或者setImageResource(int)这个方法来定义。
To indicate the different button states (focused, selected, etc.), you can define a different image for each state. E.g., a blue image by default, an orange one for when focused, and a yellow one for when pressed. An easy way to do this is with an XML drawable "selector." For example:
你可以给ImageButton不同的状态定义不同的图片,
例如默认情况是蓝色的,获得焦点时是橙色的,被点击时是黄色的。
这种效果用一个XML的drawable资源 "selector"就很容易实现了,例如:
android:drawable="@drawable/button_pressed" />
android:drawable="@drawable/button_focused" />
保存XML文件在项目的res/drawable/目录,并且将其声明为你的ImageButton的来源(就是android:src那个属性)。Android就会基于按钮的状态,自动将按钮改变为相应的图像。
【注意】上面里面的元素怎么排序很关键,因为它们是按顺序被评估的。这就是为什么 "normal"会在最后,因为“普通”的状态只会在既不是“取得焦点”状态也不是“被点击”状态时产生。(这句真的不知道怎么翻译,放原文吧。)
The order of the elements is important because they are evaluated in order. This is why the "normal" button image comes last, because it will only be applied afterandroid:state_pressed and android:state_focused have both evaluated false.
我的上机记录
刚开始只看了官网一半的介绍就开始操作,
以为跟Button的属性一样,结果发现不是。
res/layout/的布局文件:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
android:id="@+id/ib_test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ib_test" />
res/drawable/的状态:
这里我刚开始还以为要放在“res/layout/”,结果就是提示出错。
效果就是下面这样: