android Button 点击背景与文字颜色变化效果

来源:互联网 发布:linux开源软件 编辑:程序博客网 时间:2024/05/01 19:30

我最近一直在研究Button,那么话多说,我们直接来上效果和代码

正常效果:


按下效果:


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

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

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

btn_bg.xml

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

btn_color.xml

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

[html] view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns: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.       
  9.     <Button  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="按下文字会变效果"  
  13.         android:textColor="@drawable/btn_color"  
  14.         android:background="@drawable/btn_bg"  
  15.         />  
  16.     <Button  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_height="wrap_content"  
  19.         android:text="按钮被禁用"  
  20.         android:enabled="false"  
  21.         android:textColor="@drawable/btn_color"  
  22.         android:background="@drawable/btn_bg"  
  23.         />  
  24.       
  25. </LinearLayout>  
0 0
原创粉丝点击