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;
}