深入解析Android中的selector

有时候我们需要根据一个组件的不同状态来显示不同的图片,不如说一个按钮,就包含点击,聚焦,或者既不点击又不聚焦等状态,要使按钮在不同的状态下显示不同的样式或图片,这时就要用到selector,可以把组件的不同状态定义在一个xml文件中。
下面是一个实例:
EditText中随着文本框的状态来动态的改变输入的文字的颜色:

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <EditText
        android:id="@+id/edit1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@drawable/editcolor"
        />
    <EditText
        android:id="@+id/edit2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@drawable/editcolor"
        />
</LinearLayout>
Drawable文件夹下的editcolor.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true"
    android:color="#f44"
    />
    <item android:state_focused="false"
        android:color="#eee"
        />

上面定义了两个EditText,当光标处于第一个时,第二个中的文字是白色,第一个的文字是红色,当光标处于第二个时恰好相反。
也可以用两张不同的图片来表示按钮不同的状态的buttonback.xml,然后在Button中的androidbackground=”@drawable/buttonback”使用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值