从资源 ID 整数中获取颜色会出错



我创建了一个接受背景颜色 resid 和阴影颜色 resId 的自定义视图。但是当我转换资源 ID 以将它们存储在 int 变量中时。它给出错误为

Expected a color resource id (R.color.) but received an RGB integer 

以下是我的二传手方法

    @Override
    public void setBackgroundColor(@ColorRes int backgroundResId) {
        this.backgroundColor = ContextCompat.getColor(context, backgroundResId);
    }
    public void setShadowColor(@ColorRes int shadowColorId) {
        this.shadowColor = ContextCompat.getColor(context, shadowColorId);
    }

使用时显示相同的错误

public void setBackgroundColor(@ColorRes int backgroundResId) {
    this.backgroundColor = context.getResources().getColor(backgroundResId);
}

我想你在方法中传递了错误的参数setBackgroundColor.您应该以这种方式使用它:

//some code
setBackgroundColor(R.color.colorPrimary)
//some code