Android以编程方式设置按钮背景

Android以编程方式设置按钮背景

问题描述:

我想知道如何以编程方式设置按钮颜色? 我已经编写了以下代码,但失败了:

I would like to know how to set the button color programatically? I have coded the following but fails:

Button11.setBackgroundColor(R.color.red);

谢谢!

R.color.red是ID(也是int),但不是颜色.

R.color.red is an ID (which is also an int), but is not a color.

改为使用以下之一:

// If you're in an activity:
Button11.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not: 
Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red));

或者,或者:

Button11.setBackgroundColor(Color.RED); // From android.graphics.Color

或者,要获得更多专业技能:

Or, for more pro skills:

Button11.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB