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

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

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

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

或者可以这样:

Java代码
  1. XmlResourceParserxpp=Resources.getSystem().getXml(R.color.button_text);
  2. try{
  3. ColorStateListcsl=ColorStateList.createFromXml(getResources(),xpp);
  4. btn.setTextColor(csl);
  5. }catch(Exceptione){
  6. //TODO:handleexception
  7. }

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

Java代码
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <selectorxmlns: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>

更多相关文章

  1. Android(安卓)混淆代码总结 和 Android(安卓)APK反编译(最新更新
  2. Android使用MediaPlayer播放流媒体,支持远程以及本地流媒体,一行代
  3. Android实现文本折叠效果
  4. android中LinearGradient线性渐变
  5. Android(安卓)在App中启动另一个App
  6. Android使用ListView构造复杂界面,响应点击事件,通过Intent跳转act
  7. Android6.0-新控件(一)
  8. 修改Android默认启动项launcher
  9. android sdk 编译--如何将源代码加入android.jar,以及make原理

随机推荐

  1. Android网络连接处理
  2. Android端的极光配置
  3. 移动互联网盈利知识
  4. Android简单图片浏览器
  5. Android接收程序安装、替换、卸载广播
  6. android下获取无线wif信号、ssid、MAC等
  7. android简单的日期时间选择器
  8. Android(安卓)2.3 不支持印度文
  9. android wifi框架
  10. Android get property的一种方法