StateListDrawable的使用

官方文档:

Lets you assign a number of graphic images to a single Drawable and swap out the visible item by a string ID value.

It can be defined in an XML file with the <selector> element. Each state Drawable is defined in a nested <item> element. For more information, see the guide toDrawable Resources.

解释:

StateListDrawable类定义了不同状态下,与之对应的资源(更多时候是图片资源)。

StateListDrawable可以在xml文件中定义,通过<selector>标签。其中每个状态的属性(可以是设置drawable,图片资源),可以通过<item>元素来设置。


下面写的例子不是状态与图片的切换,只是简单的在状态改变时,改变字体的颜色属性。

关于StateListDrawable的详细解析,可参考Android中View(视图)绘制不同状态背景图片原理深入分析以及StateListDrawable使用详解


开始贴出小例子:

在focus.xml文件中定义StateListDrawable,设置的item主要是控制焦点获得/失去时,颜色的变化。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
	<!-- 设置控件属性,是否获得焦点 cause 显示不同颜色 -->
    <item android:state_focused="true" android:color="#f44"/>
    <item android:state_focused="false" android:color="#111"/>
</selector>

在布局文件main.xml中添加了两个EditText控件,将控件中默认字体颜色设置成focus.xml文件中控制的属性颜色。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    
<!-- android:textColor属性使用了focus.xml文件中定义的颜色 -->
    <EditText
        android:id="@+id/edit01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StateListDrawable"
        android:textColor="@drawable/focus" />

    <EditText
        android:id="@+id/edit02"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="StateListDrawable"
        android:textColor="@drawable/focus" />

</LinearLayout>

主Activity中没有添加什么语句,这样运行,就可以看到以下效果图:

上面一个EditText获得焦点时


下面一个EditText获得焦点时



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值