【问题标题】:what is the need of parsing resource id using ContextCompat class?使用 ContextCompat 类解析资源 id 的需要是什么?
【发布时间】:2018-04-01 02:00:15
【问题描述】:

在下面的代码中,我想根据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;

    }

然后我的应用程序无法运行,后来我发现我必须这样做:

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);
}

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

【问题讨论】:

  • 所以你问为什么return somethingreturn someCallToSomeMehtod(something) 不同?您不应该查看返回类型,而是查看返回值。 return 0 也会返回 int,但也可能无法正常工作。

标签: java android


【解决方案1】:

ContextCompat.getColor() 返回的int 实际上是您想要的颜色(一个十六进制颜色作为整数),在大多数情况下,您会被要求提供该颜色。 R.color.xxx int 实际上只是一个 ID,从您的资源中引用您的十六进制/整数颜色,取决于您使用的 API,您可能会被要求提供该 ID,但在幕后肯定会有一个 ContextCompat.getColor() 来自那个id。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多