---
title: "StateListDrawable资源"
author: "DanielHan"
date: "2014-07-15T21:18:16Z"
tags: []
categories: ["移动开发"]
slug: "statelistdrawable"
draft: false
lastmod: "2014-07-15T21:17:50Z"
id: 2092489
url: "https://danielhan.iteye.com/blog/2092489"
---

StateListDrawable用于组织多个Drawable对象。当使用StateListDrawable作为目标组件的背景/前景图片时，StateListDrawable对象所显示的Drawable对象会随目标组件状态的改变而自动切换。
    定义StateListDrawable对象的XML文件的根元素为<selector../>，该元素可以包含多个<item.../>元素，该元素可指定如下属性。

android:color或android:drawable：指定颜色或Drawable对象。
android:state_xxx：指定一个特定状态。

所支持的状态：

![](http://dl2.iteye.com/upload/attachment/0099/1348/c2700d46-5ca6-3d04-b635-ce572f15ea94.png)

例子：
布局文件main.xml

```xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent"
	>
<!-- 使用StateListDrawable资源 -->
<EditText  
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:textColor="@drawable/my_image"
	/>
<EditText  
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:textColor="@drawable/my_image"
	/>
</LinearLayout>

```



```xml

<?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 android:state_focused="false"
		android:color="#111"
	/>
</selector>

```



![](http://dl2.iteye.com/upload/attachment/0099/1384/62afbb48-e081-3f7f-8322-4d6e4c25ef0d.png)