文章标题

Android若一个Button中用了Selector而Selector中的两个属性冲突会怎么处理?

下边时Selector的代码:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true">
        <color android:color="#cc00ff" />
    </item>
    <item android:state_pressed="false">
        <color android:color="#FF0000" />
    </item>
</selector>

下边是布局文件的代码,只有一个Button,Background属性用上边的selector。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_selector"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/button_selector"
            android:text="会变背景的Button"/>

    </LinearLayout>

</RelativeLayout>

由以上两段代码可以看出,默认的Button中enable属性是true,pressed属性也为false,而Selector中,两种属性都定义了。那么会显示那种属性呢?运行后Button中显示的是enable中定义的颜色。
由于在selector中pressed定义在enable上边,于是探索selector中属性冲突是否显示上边的属性。将两个属性的位置对换,运行后Button显示enable中定义的颜色。

为了排除颜色覆盖的问题,于是讲enabled中的颜色设置为透明,如果运行后Button是透明的则不存在颜色覆盖问题,selector代码如下:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="true">
        <color android:color="#00cc00ff" />
    </item>
    <item android:state_pressed="false">
        <color android:color="#FF0000" />
    </item>
</selector>

运行后Button为透明的,因此不存在颜色冲突问题。

最后结论:当selector中两个属性冲突时,会选取定义在上边的属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值