【问题标题】:tinting CheckBox and RadioButton on Android在 Android 上为 CheckBox 和 RadioButton 着色
【发布时间】:2011-12-29 14:54:17
【问题描述】:

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

基本思想是检索 UI 元素的 Drawable,如果它有一个,则在其上设置颜色过滤器。我的问题是为复合按钮找到合适的 Drawable。我认为 getCompoundDrawables() 将是我需要的,但 4 个可绘制对象的返回数组始终包含 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 的可绘制对象(所有可绘制对象都是空的)。

关于如何做到这一点的任何想法?我知道我可以设置自己的自定义可绘制对象,但我更喜欢使用标准的绘制对象,如果可能的话只设置一个颜色过滤器。

【问题讨论】:

    标签: android colors checkbox filter drawable


    【解决方案1】:

    我以稍微不同的方式解决了我的问题。最终继承了 CheckBox (和 RadioButton)。在我覆盖的子类中:

    protected boolean verifyDrawable( Drawable drawable )
    

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

    【讨论】:

      【解决方案2】:

      您不会进行“正常”的非 ViewGroup 视图。此外,您的测试 for ViewGroup 在 for 循环中,只有当视图是 ViewGroup 时才能运行。

      【讨论】:

      • 不,非 ViewGroup 视图确实得到了处理(你说进步了,但我认为这就是你的意思)。设置过滤器的代码确实会为 CheckBox 调用,但它没有任何影响,因为所有 Drawable 都是空的。我已经在调试器中验证了这一点。 ViewGroup 的内部测试是针对孩子的,所以我认为这不是多余的测试。
      猜你喜欢
      • 1970-01-01
      • 2014-03-21
      • 2010-11-03
      • 2011-07-18
      • 2012-04-12
      • 2011-03-22
      • 2013-12-28
      • 2022-01-19
      • 2011-03-27
      相关资源
      最近更新 更多