Drawable资源是Android应用程序中使用最广泛的资源,也是最灵活的资源,它不仅可以直接使用*.png,*.jpg,*.gif*.9.png等图片资源,也可是使用多种XML文件作为资源。只有XML文件可以被系统编译为Drawable子类的对象,那么就可以作为Drawable资源。
1.图片资源
图片资源是最简单的Drawable资源,只要把*.png,*.jpg,*.gif*.9.png放入/res/drawable-xxxx目录下,Android SDK就会在编译映众中自动加载图片。
2.StateListDrawable资源
当使用StateListDrawable时,Drawable对象会跟随目标的状态改变而自动切换。我们从以下几个方面来了解StateListDrawable资源
1.目标组件的状态属性。
2.根据状态属性切换图片资源(组织多个Drawable对象)。
3.根元素为<selector.../>
目标组件状态
属性值 | 含义 |
android:state_active | 代表是否处于激活状态 |
android:state_checkable | 代表是否处于可勾选状态 |
android:state_checked | 代表是否处于已勾选状态 |
android:state_enable | 代表是否处于可用状态 |
android:state_first | 代表是否处于开始状态 |
android:state_focused | 代表是否处于已得到焦点状态 |
android:state_last | 代表是否处于结束状态 |
android:state_middle | 代表是否处于中间状态 |
android:state_pressed | 代表是否处于已被按下状态 |
android:state_selected | 代表是否处于已被选中状态 |
android:state_window_focus | 代表窗口是否处于已得到焦点状态 |
需要注意的是,一个窗口只能有一个视图处于获得焦点(focused)状态,但可用有多个视图处于被选中(selected)状态。focused状态一般由按键操作引起,presed状态一般由触摸操作引起,selected完全是由应用程序主动调用setSelected控制。
高亮显示正在输入的文本框
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<!-- 指定获得焦点时的颜色 -->
<item android:state_focused="true" android:color="#f44"></item>
<item android:state_focused="false" android:color="#ccf"></item>
</selector>
这样就定义了一个StateListDrawable对象,该对象要求在输入文本时,文本颜色为“#f44”,当EditText失去焦点时,文本颜色又变为“#ccf”。
3.LayerDrawable资源
LayerDrawable资源也是组织多个Drawable对象,系统会根据Drawable对象的索引大小按顺序绘制,索引大的将会被绘制在上面。我们可以从以下几个方面连了解LayerDrawable资源。
1.顺序绘制
2.大索引覆盖小索引(组织多个Drawable对象)。
3.根元素为<layer-list.../>
定制拖动条外观
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@android:id/background"
android:drawable="@drawable/grow" ></item>
<item android:id="@android:id/progress"
android:drawable="@drawable/ok"></item>
</layer-list>
布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.layerdrawable.MainActivity" >
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:progressDrawable="@drawable/my_bar"
/>
</LinearLayout>
效果如下
源码下载