【问题标题】:How to pass a resource to a method call in Android?如何将资源传递给Android中的方法调用?
【发布时间】:2016-05-20 23:32:17
【问题描述】:

目前我有一个巨大的 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);
}

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

【问题讨论】:

    标签: java android parameter-passing android-resources


    【解决方案1】:

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

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

    void setBackgroundResource (int resid)
    

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-10
      • 2012-06-15
      • 1970-01-01
      • 2014-05-02
      • 2018-09-13
      相关资源
      最近更新 更多