如何在阵列颜色中设置按钮背景?
为什么CustomButton结果为灰色?在R.color.blue中,绿色和红色真的是红色,蓝色和红色。我试图从colors.xml中随机选择颜色为红蓝绿色的按钮颜色。如何在阵列颜色中设置按钮背景?
public void CustomButton(int btnId) {
Button btn = (Button) findViewById(btnId);
int[] btnColor = { R.color.blue, R.color.green, R.color.red };
Random random = new Random();
int c = btnColor[random.nextInt(btnColor.length)];
btn.setBackgroundColor(c);
}
试试这个
你应该使用
getResources().getColor(yourcolorid)
,使色彩
小的变化在你的代码
更改此
btn.setBackgroundColor(c);
这个
btn.setBackgroundColor(getResources().getColor(c));
解决。谢谢。但我想知道为什么?您的代码和我的代码之间的区别。 – 2013-04-08 17:26:04
@CingSianDal由于您正在分配由R生成的Color的ID,但颜色的值 – Pragnani 2013-04-08 17:37:17
除非你使用自定义颜色,尝试删除 'R':
public void CustomButton(int btnId) {
Button btn = (Button) findViewById(btnId);
int[] btnColor = {Color.BLUE, Color.GREEN, Color.RED};
Random random = new Random();
int c = btnColor[random.nextInt(btnColor.length)];
btn.setBackgroundColor(c);
}
这将使用内置Android类Color。
我不想使用Color.BLUE Color.GREEN Color.ORANGE我想通过随机调用colors.xml中的颜色。请..解决it.please – 2013-04-08 17:15:10
@CingSianDal检查我的答案... – Pragnani 2013-04-08 17:22:10
我不完全确定你在做什么,但如果你想随机化按钮的颜色,我认为这可能会帮助你 - > http://*.com/questions/6185931/how-设置按钮颜色 – Hanut 2013-04-08 17:24:29