Android之drawable state各个属性详解

本文介绍如何使用状态列表Drawable为UI组件定义不同状态下的外观。通过XML文件定义各种状态及其对应的图片资源,实现按钮等组件在不同交互状态下的视觉变化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

先看一个范例:

XML file saved atres/drawable/button.xml:

[java] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <selectorxmlns:android="http://schemas.android.com/apk/res/android">
  3. <itemandroid:state_pressed="true"android:state_enabled="true"android:state_window_focused="false"
  4. android:drawable="@drawable/button_pressed"/><!--pressed,enable等多个属性-->
  5. <itemandroid:state_focused="true"
  6. android:drawable="@drawable/button_focused"/><!--focused-->
  7. <itemandroid:state_hovered="true"
  8. android:drawable="@drawable/button_focused"/><!--hovered-->
  9. <itemandroid:drawable="@drawable/button_normal"/><!--default-->
  10. </selector>


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

[java] view plain copy
  1. <Button
  2. android:layout_height="wrap_content"
  3. android:layout_width="wrap_content"
  4. android:background="@drawable/button"/>



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没有任何的状态说明,那么它将可以被任何一个状态匹配。

详细的请看官方的API,那里写的更详细~! http://developer.android.com/guide/topics/resources/drawable-resource.html#StateList
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值