Android按钮文字变色(使用 ColorStateList)
来源:互联网 发布:do while vb 编辑:程序博客网 时间:2024/05/21 07:03
在android中,对于不同的按钮状态,采用不同的颜色显示文字,实现起来非常方便。
我们首先添加一个ColorStateList资源XML文件,XML文件保存在res/color/button_text.xml:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:color="#ffff0000"/> <!-- pressed --> <item android:state_focused="true" android:color="#ff0000ff"/> <!-- focused --> <item android:color="#ff000000"/> <!-- default --></selector>
一、在xml中设置
<Button android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/green" android:paddingBottom="10dp" android:paddingTop="10dp" android:text="@string/login_text" android:textColor="@color/button_text" android:textSize="20sp" />也就是说,只要把selector设置到了android:textColor这个属性就可以了,这个和设置button的背景方法是一样的。
二、在代码中设置
如果要在代码中设置,就需要用到ColorStateList这个类了。
方法1:
Button btn=(Button)findViewById(R.id.btn);Resources resource=(Resources)getBaseContext().getResources(); ColorStateList csl=(ColorStateList)resource.getColorStateList(R.color.button_text);if(csl!=null){ btn.setTextColor(csl);}方法2:
XmlResourceParser xpp=Resources.getSystem().getXml(R.color.button_text); try { ColorStateList csl= ColorStateList.createFromXml(getResources(),xpp); btn.setTextColor(csl);} catch (Exception e) { // TODO: handle exception}
这两种方法都很简单,有木有,看个人使用习惯了。
最后列出所有可能出现的状态:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:color="hex_color" android:state_pressed=["true" | "false"] android:state_focused=["true" | "false"] android:state_selected=["true" | "false"] android:state_checkable=["true" | "false"] android:state_checked=["true" | "false"] android:state_enabled=["true" | "false"] android:state_window_focused=["true" | "false"] /></selector>
参考:http://developer.android.com/guide/topics/resources/color-list-resource.html
0 0
- Android按钮文字变色(使用 ColorStateList)
- ColorStateList按钮文字变色
- ColorStateList按钮文字变色
- Android学习 之 ColorStateList按钮文字变色
- Android学习 之 ColorStateList按钮文字变色
- Android ColorStateList 按钮 文字状态 变色
- Android学习 之 ColorStateList按钮文字变色
- Android学习 之 ColorStateList按钮文字变色
- Android学习 之 ColorStateList按钮文字变色
- Android学习 之 ColorStateList按钮文字变色
- ColorStateList改变按钮、文本框文字变色
- Android Button点击效果(按钮背景变色、文字变色)
- Android Button点击效果(按钮背景变色、文字变色)
- Android按钮设置文字变色
- Android ColorStateList使用
- Android动态实现文字颜色选择器 ColorStateList
- android的ColorStateList简单使用
- Android使用selector文件点击文字变色
- 加分二叉树_DP
- (精简)Spring框架的IoC(替代工厂类实现方法)和AOP(定义规则,约定大于配置)
- java---hashmap
- HTML5+WebGL:构建3D网页新世界
- 如何解决git工程文件冲突?
- Android按钮文字变色(使用 ColorStateList)
- JVM启动参数解析
- TwoSum
- unity3d如何有效地组织代码?
- PHP实现指定时间的n月之前的这一天的两种算法
- CVTRES : fatal error CVT1100: duplicate resource. type:DIALOG, name:1269, language:0x0804
- YII 的安全性演示代码SQL
- IOS高级教程1:处理1000张图片的内存优化
- 黑马程序员--动态代理