点击Button字体变色,图片变化,背景变化
先在values目录创建color.xml文件
<?xml version="1.0" encoding="utf-8"?> <resources> <drawable name="red">#f00</drawable> <drawable name="green">#0f0</drawable> <drawable name="gray">#ccc</drawable> </resources>
在res下新建drawable目录,里面新建btn_bg.xml和btn_color.xml文件,代码如下:
btn_bg.xml
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" 8 android:drawable="@drawable/btn_test_normal" /> 9 </selector>
btn_color.xml
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>
在布局中使用
1 <Button 2 android:layout_width="wrap_content" 3 android:layout_height="wrap_content" 4 android:text="按下文字会变效果" 5 android:textColor="@drawable/btn_color" 6 android:background="@drawable/btn_bg" 7 />