在下面的代码中,我希望根据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()方法。
发布于 2018-03-31 18:00:15
由int返回的ContextCompat.getColor()实际上是您想要的颜色(十六进制颜色作为整数),在大多数情况下,您将被要求提供该颜色。R.color.xxx int实际上只是一个从资源中引用十六进制/整数颜色的id,依赖于您正在使用的API,可能会要求您提供该ID,但是场景后面肯定会有来自该id的ContextCompat.getColor()。
https://stackoverflow.com/questions/49590729
复制相似问题