在Java代码中,使用setBackgroundResource()方法而不是setBackgroundColor()方法来设置按钮的背景。 setTextColor()方法的工作原理相同。
示例:
Button button = findViewById(R.id.button);
button.setBackgroundResource(R.color.red);
button.setTextColor(R.color.white);
请确保在colors.xml文件中正确定义了颜色。