【问题标题】:Getting real color of a ViewGroup and compare with resource color获取 ViewGroup 的真实颜色并与资源颜色进行比较
【发布时间】:2017-05-20 05:47:52
【问题描述】:

我正在尝试获取 ViewGroup 的颜色并尝试与资源颜色进行比较。

这是我的代码

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:id="@+id/mainLayout"
                android:background="@color/colorPrimary"
                android:layout_height="match_parent"
                >

在我的代码中我正在这样做。

ViewGroup mainLayout = (ViewGroup) findViewById(R.id.mainLayout);
        ColorDrawable viewColor = (ColorDrawable) mainLayout.getBackground();
        if (viewColor != null)
        {
            int colorId = viewColor.getColor(); // i get -6371612
            int mainColor = getResources().getColor(R.color.colorPrimary); // i get -65536
            if (colorId == mainColor)
            {
                mainLayout.setBackgroundColor(Color.RED);
            }
        }

colorId 和 mainColor 不相同。我错过了什么?他们不应该一样吗?

【问题讨论】:

    标签: java android android-studio material-design


    【解决方案1】:

    我刚刚检查了您的代码,它运行良好(颜色经过比较并且相等)。

    但是:当我将RelativeLayout 的背景颜色设置为Color.RED 时,我也得到了您收到的 -65536。

    换一种说法:您的代码工作正常,但该函数被调用了两次,第一次将布局的颜色设置为红色(如代码指示的那样),然后当您尝试检查颜色不匹配(因为一个是红色,另一个是 colorPrimary。

    【讨论】:

    • 在这种情况下,OP 在问题中也必须以错误的方式获取值。
    • 不,值很好.. @+id/mainLayout 在第一次(成功)通过时刚刚从 colorPrimary 切换到 RED
    • 他从一个常数值得到mainColor,所以它不能改变。我认为这只是一个错字,你是对的。
    • 啊,现在我明白你的意思了.. 你说得对,这可能只是一个错字
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-18
    • 1970-01-01
    • 2017-07-09
    相关资源
    最近更新 更多