StateListDrawable不生效

StateListDrawable无法选择状态

前言

  • 最近将项目代码重构了一下,提取出一个Banner类。但是在Banner中书写的StateListDrawable的Selected属性不生效。下面是代码

    private Drawable getSelectorDrawable() {
            StateListDrawable stateListDrawable = new StateListDrawable();
    
            stateListDrawable.addState(new int[]{}, getGradientDrawable(Color.BLACK));
            stateListDrawable.addState(new int[]{android.R.attr.state_selected}, getGradientDrawable(Color.WHITE));
            return stateListDrawable;
        }
    

分析

  • 当设置选中的时候,也没有view的形状改变了,但是选中的颜色没有改变。通过打印发下view的状态是 android.R.attr.state_window_focused;
  • 形状发生了改变,但是颜色没有改变。说明一直是默认的状态。也就是一直是new int[]{}这个状态。
  • 是不是我们应该明确指定selected=false这种状态呢?
  • 分析我们在xml中写selector的时候,有selected=true和selected=false;那么java代码有没有办法明确的设置选中。非选中呢?

发现

  • 如果说android.R.attr.state_selected为true的话,那么-android.R.attr.state_selected为false,注意前面的负号。

改正

    private Drawable getSelectorDrawable() {
            StateListDrawable stateListDrawable = new StateListDrawable();
            // 明确指定状态,当没有选中的时候
            stateListDrawable.addState(new int[]{-android.R.attr.state_selected}, getGradientDrawable(Color.BLACK));
            stateListDrawable.addState(new int[]{android.R.attr.state_selected}, getGradientDrawable(Color.WHITE));
            return stateListDrawable;
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值