在Android上对CheckBox和RadioButton进行着色

时间:2011-11-15 15:07:50

标签: android colors checkbox filter drawable

我有一个Android天文学应用程序,我需要在晚上使用偏红色UI。虽然我有一个适用于许多(大多数??)UI元素的方案,但我在使用CompoundButtons时遇到问题:CheckBox和RadioButton。

基本思想是为UI元素检索Drawable,如果有,则在其上设置一个颜色过滤器。我的问题是为复合按钮找到合适的Drawable。我认为getCompoundDrawables()将是我需要的,但是4个drawable的返回数组总是包含4个元素的空值。

这是我在顶级视图上调用的递归代码,试图对UI元素进行着色。

public static void setNightVisionBkg( View view )
{
    if ( view instanceof ViewGroup )
    {
        Drawable drawable = view.getBackground();
        if ( drawable != null )
            drawable.setColorFilter( 0xFFAA0000, PorterDuff.Mode.MULTIPLY );

        ViewGroup group = (ViewGroup) view;
        int numChildren = group.getChildCount();
        for ( int i = 0; i < numChildren; i++ )
        {
            View v = group.getChildAt( i );
            Drawable d = v.getBackground();
            if ( d != null )
                d.setColorFilter( 0xFFAA0000, PorterDuff.Mode.MULTIPLY );

            if ( v instanceof ViewGroup )
            {
                setNightVisionBkg( (ViewGroup) v );
            }
            else if (v instanceof CompoundButton)
            {
                CompoundButton compBtn = (CompoundButton)v;
                Drawable drawables[] = compBtn.getCompoundDrawables();
                for (int j = 0; j < drawables.length; j++)
                if (drawables[j] != null)
                {
                    drawables[j].setColorFilter( 0xFFAA0000, PorterDuff.Mode.MULTIPLY );
                }
            }
        }
    }
}

请注意,它是后一部分,它使得CompoundButton的Drawables无法工作(所有drawables都为null)。

有关如何做到这一点的任何想法?我知道我可以设置我自己的自定义drawables,但我更喜欢使用标准的drawable,如果可能的话只设置一个colorFilter。

2 个答案:

答案 0 :(得分:2)

我以稍微不同的方式解决了我的问题。结束了CheckBox(和RadioButton)的子类化。在子类中,我重写:

protected boolean verifyDrawable( Drawable drawable )

在这个方法中我在colorable上设置了colorFilter。效果很好。

答案 1 :(得分:0)

您不会进行“普通”非ViewGroup视图。此外,你的测试 for for循环中的ViewGroup,如果视图是ViewGroup,则只能运行。