第二个参数类型错误

时间:2017-03-01 18:13:32

标签: android android-layout android-studio

我想为我的布局设置背景颜色。 问题是它给了我:

错误的第二个参数类型。必需的。 我只是将R.color.red更改为color variable

  //add background color header
        String color = pref.getString("color", null);
        if(color != null) {
            color = "R.color." + color;
            LinearLayout rl = (LinearLayout) findViewById(R.id.menuHeader);
            rl.setBackgroundColor(ContextCompat.getColor(this, color));
        }

有什么不对?怎么解决?

3 个答案:

答案 0 :(得分:2)

ContextCompat.getColor正在等待R.color.red之类的内容,实际上类型为int。你传递的是String,当然这是错误的。

你应该这样做:

String color = pref.getString("color", null);
if(color != null) {
      int colorId = this.getResources().getIdentifier(color, "color", this.getPackageName());
      LinearLayout rl = (LinearLayout) findViewById(R.id.menuHeader);
      rl.setBackgroundColor(ContextCompat.getColor(this, colorId));
}

此外,如果X获得color,请确保您的颜色名称为:  <color name="X">#000000</color>

答案 1 :(得分:1)

color应为int。

所以将代码更改为:

    String colorString = pref.getString("color", null);
    if(colorString != null) {
        colorString = "R.color." + colorString;

        int myColor = ContextCompat.getColor(this, colorString);

        LinearLayout rl = (LinearLayout) findViewById(R.id.menuHeader);
        rl.setBackgroundColor(ContextCompat.getColor(this, myColor));
    }

答案 2 :(得分:1)

为什么不能保存颜色的String值呢?

String color = getResources().getString(R.color.red);

将此保存为共享首选项,因此值为#123456 然后从共享首选项String color = pref.getString("color", null);中获取它 然后是rl.setBackgroundColor(Color.parseColor(color));

相关问题