使用ContextCompat类解析资源id的需求是什么?

时间:2018-03-31 17:52:54

标签: java android

在下面的代码中,我想根据getMagnitudeColor()方法中的情况返回某种颜色的资源ID。 所以,如果我像这样直接返回它们

private int getMagnitudeColor(double magnitude){
    int roundOffMagnitude = (int)Math.floor(magnitude);

    switch(roundOffMagnitude){
        case 1: return R.color.magnitude1;
        case 2: return R.color.magnitude2;
        case 3: return R.color.magnitude3;
        case 4: return R.color.magnitude4;
        case 5: return R.color.magnitude5;
        case 6: return R.color.magnitude6;
        case 7: return R.color.magnitude7;
        case 8: return R.color.magnitude8;
        case 9: return R.color.magnitude9;

        default: return R.color.magnitude10plus;

    }

image of the above code

然后我的应用程序以后没有工作我发现我要做这样的事情:

private int getMagnitudeColor(double magnitude) {
    int magnitudeColorResourceId;
    int magnitudeFloor = (int) Math.floor(magnitude);
    switch (magnitudeFloor) {
        case 0:
        case 1:
            magnitudeColorResourceId = R.color.magnitude1;
            break;
        case 2:
            magnitudeColorResourceId = R.color.magnitude2;
            break;
        case 3:
            magnitudeColorResourceId = R.color.magnitude3;
            break;
        case 4:
            magnitudeColorResourceId = R.color.magnitude4;
            break;
        case 5:
            magnitudeColorResourceId = R.color.magnitude5;
            break;
        case 6:
            magnitudeColorResourceId = R.color.magnitude6;
            break;
        case 7:
            magnitudeColorResourceId = R.color.magnitude7;
            break;
        case 8:
            magnitudeColorResourceId = R.color.magnitude8;
            break;
        case 9:
            magnitudeColorResourceId = R.color.magnitude9;
            break;
        default:
            magnitudeColorResourceId = R.color.magnitude10plus;
            break;
    }

    return ContextCompat.getColor(getContext(), magnitudeColorResourceId);
}

image for the above code

我知道ContextCompat.getColor用于解析颜色资源ID,但我的问题是,如果资源id和ContextCompat.getColor()返回的值都是整数,那么需要使用{{1}方法。

1 个答案:

答案 0 :(得分:1)

int返回的ContextCompat.getColor()实际上是您想要的颜色(十六进制颜色为整数),在大多数情况下,系统会要求您提供该颜色。 R.color.xxx int实际上只是一个引用您的资源的十六进制/整数颜色的ID,依赖于您正在使用的API,可能会要求您提供该ID,但在场景后面肯定会有{{{ 1}}来自那个id。