android的空间样式主要包括控件各种状态下背景图片或颜色,控件中字体颜色。
这里解释一下个状态是什么意思,android中控件有如下几个状态
state_enabled 是否有效
state_focused 是否聚焦
state_pressed 是否被按下
在res/drawable文件夹新增一个文件,此文件设置了图片的触发状态,你可以设置 state_pressed,state_checked,state_pressed,state_selected,state_focused,state_enabled 等几个状态:
定义按钮背景
button_bg.xml
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="true"
android:drawable="@drawable/button_focused" />
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/button_focused" />
<item android:state_focused="true"
android:drawable="@drawable/button_focused" />
<item android:state_focused="false"
android:drawable="@drawable/button_defocused" />
</selector>
定义button_focused时的状态
button_focused.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:startColor="#505050" android:endColor="#C0C0C0"
android:paddingTop="5dp" android:angle="0" />
<corners android:radius="5dp" />
<stroke android:width="2dp" android:color="#FFFF9200" />
</shape>
定义button_defocused的状态
button_defocused.xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient android:startColor="#505050" android:endColor="#C0C0C0"
android:paddingTop="5dp" android:angle="0" />
<corners android:radius="5dp" />
</shape>
定义的button_focused.xml和button_defocused.xml可产生动态效果,如果不想这样可在button_bg.xml 中把
android:drawable="@drawable/button_focused"直接替换为图片资源,如:
android:drawable="@drawable/focus",此时在res/drawable目录下要有focus.png资源
字体颜色配置文件:
button_font.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:color="#FFF" />
<item android:state_focused="true" android:color="#FFF" />
<item android:state_pressed="true" android:color="#FFF" />
<item android:color="#000" />
</selector>
引用的方法:在main.xml中将button_bg赋值给Button组件中的background属性。
<Button
android:id="@+id/myButton1"
android:background="@drawable/button_bg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/str_button1"
android:textColor="@drawable/button_font"
/>
通过上述方法即可在焦点和非焦点状态下来动态改变按钮的背景,字体颜色。