android按钮被点击文字颜色变化效果

原文链接:http://blog.csdn.net/maylian7700/article/details/6978131


有的时候做应用需要点击按钮时文字颜色也跟着变,松开后又还原,目前发现两种解决方案:第一用图片,如果出现的地方比较多,那么图片的量就相当可观;第二,也就是本文讲到的。废话少说,先贴图片,再上代码。

正常效果:


按下效果:


先在values目录创建color.xml文件,在里面加入以下自定义颜色(注意不是用color标签)的代码:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <resources>
  3. <drawablename="red">#f00</drawable>
  4. <drawablename="green">#0f0</drawable>
  5. <drawablename="gray">#ccc</drawable>
  6. </resources>

然后在res下新建drawable目录,里面新建btn_bg.xml和btn_color.xml文件,代码如下:

btn_bg.xml

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <selectorxmlns:android="http://schemas.android.com/apk/res/android">
  3. <itemandroid:state_window_focused="false"android:state_enabled="true"
  4. android:drawable="@drawable/btn_test_normal"/>
  5. <itemandroid:state_enabled="false"android:drawable="@drawable/btn_test_normal"/>
  6. <itemandroid:state_pressed="true"android:drawable="@drawable/btn_test_press"/>
  7. <itemandroid:state_focused="true"android:drawable="@drawable/btn_test_normal"/>
  8. </selector>

btn_color.xml

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <selectorxmlns:android="http://schemas.android.com/apk/res/android">
  3. <itemandroid:state_focused="false"android:state_enabled="true"android:state_pressed="false"
  4. android:color="@drawable/red"/>
  5. <itemandroid:state_enabled="false"android:color="@drawable/gray"/>
  6. <itemandroid:state_pressed="true"android:color="@drawable/green"/>
  7. <itemandroid:state_focused="true"android:color="@drawable/red"/>
  8. </selector>
最后是测试用的布局文件:

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:background="@android:color/white"
  7. >
  8. <Button
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="按下文字会变效果"
  12. android:textColor="@drawable/btn_color"
  13. android:background="@drawable/btn_bg"
  14. />
  15. <Button
  16. android:layout_width="wrap_content"
  17. android:layout_height="wrap_content"
  18. android:text="按钮被禁用"
  19. android:enabled="false"
  20. android:textColor="@drawable/btn_color"
  21. android:background="@drawable/btn_bg"
  22. />
  23. </LinearLayout>

OK,大功告成!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值