---
title: "Android之drawable state各个属性详解"
author: "gybin"
date: "2015-12-31T17:32:03Z"
tags: []
categories: ["移动开发"]
slug: "android-drawable-state"
draft: false
lastmod: "2015-12-31T17:32:03Z"
id: 2267934
url: "https://gybin.iteye.com/blog/2267934"
---

Via ;http://blog.csdn.net/leasystu/article/details/7250885

我们在定义一个drawable的时候可以通过xml定义的drawable对象。它使得一个图片能在不同的状态下显示不同的图案，比如一个Button，它有pressed，focused，或者其它状态，通过使用state list drawable，你就可以为每种状态提供不同的图片。

先看一个范例：

XML file saved at `res/drawable/button.xml`:

 

**\[java]** [view plain](http://blog.csdn.net/leasystu/article/details/7250885 "view plain")[copy](http://blog.csdn.net/leasystu/article/details/7250885 "copy")

 

01. &lt;?xml version="1.0" encoding="utf-8"?&gt;
02. &lt;selector xmlns:android="http://schemas.android.com/apk/res/android"&gt;
03. &lt;item android:state\_pressed="true" android:state\_enabled="true" android:state\_window\_focused="false"
04. android:drawable="@drawable/button\_pressed" /&gt; &lt;!-- pressed,enable等多个属性 --&gt;
05. &lt;item android:state\_focused="true"
06. android:drawable="@drawable/button\_focused" /&gt; &lt;!-- focused --&gt;
07. &lt;item android:state\_hovered="true"
08. android:drawable="@drawable/button\_focused" /&gt; &lt;!-- hovered --&gt;
09. &lt;item android:drawable="@drawable/button\_normal" /&gt; &lt;!-- default --&gt;
10. &lt;/selector&gt;

 

This layout XML applies the state list drawable to a Button:

**\[java]** [view plain](http://blog.csdn.net/leasystu/article/details/7250885 "view plain")[copy](http://blog.csdn.net/leasystu/article/details/7250885 "copy")

 

1. &lt;Button
2. android:layout\_height="wrap\_content"
3. android:layout\_width="wrap\_content"
4. android:background="@drawable/button" /&gt;

android:drawable 放一个drawable资源  
android:state\_pressed 是否按下，如一个按钮触摸或者点击。  
android:state\_focused 是否取得焦点，比如用户选择了一个文本框。  
android:state\_hovered 光标是否悬停，通常与focused state相同，它是4.0的新特性  
android:state\_selected 被选中，它与focus state并不完全一样，如一个list view 被选中的时候，它里面的各个子组件可能通过方向键，被选中了。  
android:state\_checkable 组件是否能被check。如：RadioButton是可以被check的。  
android:state\_checked 被checked了，如：一个RadioButton可以被check了。  
android:state\_enabled 能够接受触摸或者点击事件  
android:state\_activated 被激活(这个麻烦举个例子，不是特明白)  
android:state\_window\_focused 应用程序是否在前台，当有通知栏被拉下来或者一个对话框弹出的时候应用程序就不在前台了

 

注意:如果有多个item，那么程序将自动从上到下进行匹配，最先匹配的将得到应用。（不是通过最佳匹配）  
如果一个item没有任何的状态说明，那么它将可以被任何一个状态匹配。