首页 文章

setColorFilter设置的颜色在prelollipop设备上消失

提问于
浏览
0

我有一个带有图标的TabLayout . 想法是改变颜色运行时 . 我有和xml可绘制文件的状态:state_pressed,state_selected和默认使用相同的白色图片,所以我可以稍后添加颜色 . 我将抽签用于不同的状态:

Drawable [] drawables = stateListDrawable.getConstantState();

并且对于每个可绘制状态,我将颜色放在另一个数组中:

drawables [i] .setColorFilter(colors [i],PorterDuff.Mode.MULTIPLY);

问题是颜色在开始时是可见的,但是当我开始点击图标时,所有图标再次变为白色并且我失去了色调 .

棒棒糖及以上的一切都按预期工作 .

2 回答

  • 0

    使用v4支持库中的tint方法

    drawables[i] = DrawableCompat.wrap(drawables[i])
    DrawableCompat.setTint(drawables[i], colors[i])
    
  • 0

    我找到了我的解决方案,看起来并不干净,但至少它正在工作:)

    我创建了CustomStateListDrawable,它从StateListDrawable扩展并添加了不同状态的drawable . 然后我重写了类中的所有方法,看看哪些方法被调用并试图改变那里的颜色 . 被调用的时间足够长(我的更改在制作之后不会被覆盖)是getState() . 我还创建了一个ColorStateList对象来保存我的颜色,所以代码看起来像这样:

    private ColorStateList colorStateList;
    
    
            public int[] getState() {
                    if (colorStateList != null) {
                        // Resolve the color for the current state
                        int color = colorStateList.getColorForState(super.getState(), 0);
                        // Get the current drawable and changed its color. 
                        if (getCurrent() != null) {
                            getCurrent().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
                        }
                    }
                    return super.getState();
                }
    

    基本上每当状态发生变化时,我都会得到当前可绘制的颜色并改变它的颜色 .

相关问题