第86页
创建一个StateListDrawable资源后,可以将该文件放置在res\drawable-xxx目录下,然后在相应的组件中使用该资源即可。例如,要在编辑框中使用名称为edittext_focused.xml的StateListDrawable资源,可以使用下面的代码:
android:id="@+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="@drawable/edittext _ focused"
android:text="请输入文字" />
8.6.3 范例1:使用9-Patch图片实现不失真按钮背景
例8.3 在Eclipse中创建Android项目,名称为8.3,实现应用9-Patch图片作为按钮的背景,并让按钮背景随按下状态动态改变。(实例位置:光盘\TM\sl\8\8.3)
(1)打开Draw 9-patch工具,在该工具中,将已经准备好的green1.png和red.png图片制作成9-Patch图片。最终完成后的图片如图8.7所示。
图8.7 完成后的图片
(2)修改新建项目的res\layout目录下的布局文件main.xml,在默认添加的垂直线性布局管理器中,将默认添加的TextView组件删除,然后添加3个Button组件,并为各按钮设置背景,其中第1个按钮的背景设置为普通PNG图片,第2个按钮的背景设置为9-Patch图片,第3个按钮的背景设置为StateListDrawable资源(用于让按钮的背景图片随按钮状态而动态改变),关键代码如下:
android:id="@+id/button1"
android:background="@drawable/green1"
android:layout_margin="5px"
android:layout_width="match_parent"
android:layout_height="50px"
android:text="我是普通图片背景"/>
android:id="@+id/button2"
android:background="@drawable/green"
android:layout_margin="5px"
android:layout_width="450px"
android:layout_height="150px"
android:text="我是9-Patch图片背景(按钮宽度和高度固定)"
/>
android:id="@+id/button3"
android:background="@drawable/button_state"
android:layout_margin="5px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="我是9-Patch图片背景(单击会变色)"
/>
(3)在res\drawable-mdpi目录中,创建一个名称为button_state.xml的StateListDrawable资源文件,在该文件中,分别指定android:state_pressed属性为true时使用的背景图片和android:state _pressed属性为false时使用的背景图片,这两张图片均为9-Patch图片。button_state.xml文件的具体代码如下:
运行本实例,将显示如图8.8所示的运行结果。其中,第一个按钮采用的是普通PNG图片,效果失真,而后面两个则采用9-Patch图片,效果没有失真。另外,在最后一个按钮上按下鼠标后,按钮的背景将变成红色,释放鼠标后,又变回绿色。
图8.8 使用9-Patch图片实现不失真按钮背景
8.6.4 范例2:控制按钮是否可用
例8.4 在Eclipse中创建Android项目,名称为8.4,实现当按钮为可用状态时,使用绿色背景;为不可用状态时,使用灰色背景。(实例位置:光盘\TM\sl\8\8.4)
(1)打开Draw 9-patch工具,制作如图8.9所示的3张9-Patch图片。
图8.9 制作完成的9-Patch图片
(2)在res\drawable-mdpi目录中,创建一个名称为button_state.xml的StateListDrawable资源文件,在该文件中,分别指定android:state_enabled属性为true时使用的背景图片(green.9.png)和android:state_enabled属性为false时使用的背景图片(grey.9.png)。button_state.xml文件的具体代码如下:
(3)修改新建项目的res\layout目录下的布局文件main.xml,在默认添加的垂直线性布局管理器中,将默认添加的TextView组件删除,然后添加两个Button组件,并为各按钮设置背景,其中第一个按钮的背景设置为StateListDrawable资源(用于让按钮的背景图片随按钮状态而动态改变),第二个按钮的背景设置为9-Patch图片red.9.png,关键代码如下: