Android学习 之 ColorStateList按钮文字变色

 

 

API

 

Windows平台VC,对于不同的按钮状态,采用不同的颜色显示文字,实现起来比较复杂,一般都得自绘按钮。但是Android里面实现起来非常方便。 

我们首先添加一个ColorStateList资源XML文件,XML文件保存在res/color/button_text.xml:

Java代码 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:state_pressed="true"  
  4.           android:color="#ffff0000"/> <!-- pressed -->  
  5.     <item android:state_focused="true"  
  6.           android:color="#ff0000ff"/> <!-- focused -->  
  7.     <item android:color="#ff000000"/> <!-- default -->  
  8. </selector>  

 

Java代码 
  1. Button btn=(Button)findViewById(R.id.btn);  
  2. Resources resource=(Resources)getBaseContext().getResources();   
  3. ColorStateList csl=(ColorStateList)resource.getColorStateList(R.color.button_text);  
  4. if(csl!=null){  
  5.      btn.setTextColor(color_state_list);//设置按钮文字颜色  
  6. }  

 

或者可以这样:

 

 

Java代码  收藏代码
  1. XmlResourceParser xpp=Resources.getSystem().getXml(R.color.button_text);   
  2. try {  
  3.      ColorStateList csl= ColorStateList.createFromXml(getResources(),xpp);  
  4.      btn.setTextColor(csl);  
  5. catch (Exception e) {  
  6.      // TODO: handle exception  
  7. }  

 

最后附上所有可能出现的状态:

Java代码  收藏代码
  1. <?xml version="1.0" encoding="utf-8"?>  
  2.    <selector xmlns:android="http://schemas.android.com/apk/res/android" >  
  3.        <item  
  4.            android:color="hex_color"  
  5.            android:state_pressed=["true" | "false"]  
  6.            android:state_focused=["true" | "false"]  
  7.            android:state_selected=["true" | "false"]  
  8.            android:state_active=["true" | "false"]  
  9.            android:state_checkable=["true" | "false"]  
  10.            android:state_checked=["true" | "false"]  
  11.            android:state_enabled=["true" | "false"]  
  12.            android:state_window_focused=["true" | "false"] />  
  13.    </selector>  
posted @   brave-sailor  阅读(683)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
历史上的今天:
2017-05-02 Android开发之蓝牙(Bluetooth)操作(二)--修改本机蓝牙设备的可见性,并扫描周围可用的蓝牙设备
2017-05-02 Android开发之蓝牙(Bluetooth)操作(一)--扫描已经配对的蓝牙设备
2017-05-02 Android中的Surface和SurfaceView
2017-05-02 Android - TextureView, SurfaceView和GLSurfaceView 以及 SurfaceTexture
2017-05-02 Android 5.0(Lollipop)中的SurfaceTexture,TextureView, SurfaceView和GLSurfaceView
2017-05-02 Android TextureView简易教程
2017-05-02 android中文网站
点击右上角即可分享
微信分享提示