selector使用
selector主要用于点击按钮或者一些控件时可以产生动态的点击效果,使用户获得更好的体验。下面介绍一下它的使用方式:
1.首先在res下建立drawable目录,然后在drawable目录下新建btn_select.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 默认时的背景图片
<item android:drawable="@drawable/pic1"/>
-->
<!-- 没有焦点时的背景图片 -->
<item android:drawable="@drawable/startnormal" android:state_window_focused="false"/>
<!-- 非触摸模式下获得焦点并单击时的背景图片
<item android:drawable="@drawable/pic2" android:state_focused="true" android:state_pressed="true"/>
-->
<!-- 触摸模式下单击时的背景图片 -->
<item android:drawable="@drawable/startpress" android:state_focused="false" android:state_pressed="true"/>
<!-- 选中时的图片背景
<item android:drawable="@drawable/pic4" android:state_selected="true"/>
-->
<!-- 获得焦点时的图片背景
<item android:drawable="@drawable/pic5" android:state_focused="true"/>
-->
</selector>
2.如何使用已经建立的btn_select.xml?
android:background="@drawable/btn_select"
注:在button按钮中添加如上属性就ok了!
3.此时我们已经实现了点击按钮背景切换的效果,那么如果点击按钮切换字体颜色呢?
其实原理差不多,大同小异,首先在res/values目录下新建color.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<drawable name="normal_color">#ff4500</drawable>
<drawable name="press_color">#434523</drawable>
</resources>
然后在res/drawable目录下新建btn_press_color.xml:
这里写代码片<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="false" android:state_enabled="true" android:state_pressed="false"
android:color="@drawable/normal_color" />
<item android:state_pressed="true" android:color="@drawable/press_color" />
</selector>
最后在控件中使用就可以了,颜色使用是textcolor属性:
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/btn_select"
android:text="@string/btn_text"
android:textColor="@drawable/btn_press_color"
android:textSize="22sp"
android:textStyle="bold"
/>