关于selector和ColorStateList的使用
android开发时,很多时候我们要动态为各种控件设置背景和前景。其中一种方法是在程序代码中的各个时间响应函数如onClick、onFocus等中为控件设定背景。然而,这种方法实现起来不仅繁琐,而且常常不仅人意。不用担心,其实实现这种功能有一个捷径(虽然有人说捷径往往是到达目标最远的路,但是我还是乐此不疲)。这个捷径就是使用android里面的selector。
Selector是一个选择器,可以根据控件的状态来选择响应的资源(如背景图,颜色值)。下面是个例子,力求简单,只为说明问题。
Selector.xml
<?xml version="1.0" encoding="utf-8" ?>
<selectorxmlns:android=
"http://schemas.android.com/apk/res/android">
<item android:state_pressed="true"android:color="#ff0000" />
<item android:color="#00ff00" />
</selector>
Main.xml中Button定义如下:
<Button android:id="@+id/btn_listen"
android:layout_width="fill_parent"
android:layout_height="wrap_contet"
android:background="R.drawable.Selector"
/>
则该Button颜色在按下的时候会是红色(#ff0000),没有按下的时候会是绿色(#00ff00)。
用法就如此简单。
其实selector提供给我们的不仅仅是以上的state_pressed属性,还有更多可用的属性让我们完成更加复杂的功能。
可用的属性有:
1、state_pressed
2、state_focused
3、state_selected
4、state_checkable
5、state_checked
6、state_enabled
7、window_focused
然后可以用这些属性的各种值的组合来定义selector里面的一个item。
Selector会为我们根据控件当前状态从中选择一个匹配的item然后将空间的背景设为所选item里面的背景。匹配算法是从第一个item开始逐个比较,找到相应的item,如果没有最后一个将作为默认的匹配item。Item匹配的条件是item中定义的属性状态和当前控件状态一样,如果某个属性在该item中没有定义,则视为自动匹配。
上述方法是在xml中为控件指定了背景,也可以在程序中动态指定背景或者其他属性。下面以指定一个控件的字体颜色为例。
大体上可以分为
1、创建xml解释器
2、创建ColorStateList
3、用前面定义的ColorStateList为控件设定字体颜色
//步骤一
XmlResourceParser xpp=Resources.getSystem().getXml
(R.color.wblog_listitem_text_selector);
try {
//步骤二
ColorStateList csl= ColorStateList.createFromXml(getResources(),
xpp);
//步骤三
btnSendPrivateMsg.setTextColor(csl);
} catch (Exception e) {
// TODO: handle exception
}
以下是3个相关内容的网址,很有参考价值,谢谢各位博主!
http://groups.google.com/group/android-beginners/browse_thread/thread/d96f3a8e6213b67f ColorStateList用法
http://www.cnblogs.com/xirihanlin/archive/2010/06/14/1758145.html android Drawable资源
http://www.cnblogs.com/xirihanlin/archive/2010/06/11/1756121.html ColorStateList用法