获取视图组的真实颜色并与资源颜色进行比较



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

这是我的代码

<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 并不相同。我错过了什么?他们不应该是一样的吗?

我刚刚检查了您的代码,它完美无缺(颜色进行比较并且相等)。

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

所以换句话说:你的代码工作正常,但该函数被调用两次,第一次它将布局的颜色设置为红色(按照代码指示),然后当你尝试检查颜色不匹配时(因为一个是红色,另一个是 colorPrimary。

最新更新