Selector-背景选择器

1.主要属性

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    
    <!-- 控件可用时 -->
    <item android:drawable="@drawable/enable" android:state_enabled="false"/>
    <!-- 当前窗口失去焦点时 -->
    <item android:drawable="@drawable/lost_window_focused" android:state_window_focused="false"/>
    <!-- 被激活时 -->
    <item android:drawable="@drawable/activated" android:state_activated="true" />
    <!--获得焦点时-->
    <item android:drawable="@drawable/focused" android:state_focused="true"/>

    <!--被按压时-->
    <item android:drawable="@drawable/pressed" android:state_pressed="true"/>
    <!--被选中时-->
    <item android:drawable="@drawable/selected" android:state_selected="true"/>
    <!--默认状态-->
    <item android:drawable="@drawable/default"/>
</selector>

使用方式: android:src="@drawable/bg_test"

注意:默认状态需要写在最后。

因为Item是从上往下匹配的,如果匹配到合适的,就不会再往下匹配了,

就是说如果默认状态写在最上方,则只会匹配默认状态,不会往下走。

2.另外除了可以设置背景图片外,还可以设置文本颜色

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <!--选中状态时-->
    <item android:color="@android:color/holo_blue_light" android:state_selected="true"/>
    <!--默认状态-->
    <item android:color="@android:color/black"/>
</selector>

使用方式: android:textColor="@drawable/text_color"


另外有一点需要注意注意的是,当你想给TextView,ImageView或者Button设置选中时背景图片,需要在控件被点击后,动态设置 btn.setSelected(true); 切记,切记。

Last modification:July 12th, 2020 at 08:21 pm