如何将资源传递给 Android 中的方法调用?

How to pass a resource to a method call in Android?

目前我有一个巨大的 switch-case 语句,我想对其进行简化。我想将所有重复的语句提取到一个方法中,并使用适当的参数调用该方法。现在的示例可能是:

switch (colouprivate void setRoundCornersStyle(Resources resource){
    chooseCategory_spinner.setBackgroundResource(resource);r) {
        case "#FF9800":
            spinner1.setBackgroundResource(R.drawable.orange);
            spinner2.setBackgroundResource(R.drawable.orange);                
            break;

这是缩短的地方。所有调用都是相同的,唯一的区别是传递的实际颜色。

到位的问题如下,我们如何将资源传递给Android中的方法调用,像这样:

case "#FF9800":
    setRoundCornerStyle(R.drawable.orange);

private void setRoundCornersStyle(Resources resource){
    spinner1.setBackgroundResource(resource);
}

我希望通过这种方式我能够实际提取所有重复项并使其清晰简单。欢迎提出任何建议!

存储在R对象中的资源标识符实际上只不过是一堆整数,代表实际资源。

你也可以看到这个in the API docs。视图的 setBackgroundResource 方法的签名如下所示:

void setBackgroundResource (int resid)

因此,您可以将资源 ID 作为 int 传递到您的方法中:

private void setRoundCornersStyle(int resource){
  spinner1.setBackgroundResource(resource);
}