初衷是想实现一个有自定义显示效果的按钮
自定义显示效果就是选中或者按下按钮的时候显示自己的图片,这个效果用以下方法实现了:
在res/drawable下新建selector.xml文件
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="true" android:drawable="@drawable/home1" /> <item android:state_pressed="true" android:drawable="@drawable/home1" /> <item android:drawable="@drawable/home0" /> </selector>
这里详细说一下state也就是当前控件的状态:
普通
state_enabled 是否有效
state_focused 是否聚焦
state_pressed 是否被按下
其中state_focused 和 state_pressed 可自由有如下4种组合
android:state_focused="true" android:state_pressed="true"
android:state_focused="true" android:state_pressed="false"
android:state_focused="false" android:state_pressed="true"
android:state_focused="false" android:state_pressed="false"
可以看出android控件有着很多不同状态,在不同的状态下有着不同的样式,比如不同的背景,请注意android控件的背景绝大部份是使用图片表示。
<ImageButton android:id="@+id/home_ib1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_below="@id/home_iv1" android:layout_marginTop="15dip" android:background="@drawable/home0" android:gravity="center" android:text="@string/home_b1" />
但是有个问题,这里我设置的text没有显示,原来ImageButton 继承自ImageView ,而非Button,所以没法在上面设置文字。
但是实现的效果的方法还是有很多种的比如在图片上绘制要显示的文字,用textview,button都可以实现。