5单击按钮可将对象颜色更改为五种不同的连续颜色



在我的android项目中,在一个屏幕上,我有一个按钮和一个黑色背景的单独对象。当我点击按钮时,单独的物体颜色应该变为白色,下一次点击它应该变为黄色,然后是橙色,然后是红色。

我已经搜索了好几个星期,试图找到一些东西来帮助我的项目,在Windows7电脑上使用android studio和java。提前感谢的任何帮助

活动中的代码应该如下所示:

int counter = -1;
int[] colors = {0xffffffff, 0xffffff00, 0xffff6600, 0xffff0000, 0xff000000};
Button buttonColored;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
buttonColored = (Button) findViewById(R.id.buttonColored);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
counter++;
if (counter > colors.length - 1) {
counter = 0;
}
buttonColored.setBackgroundColor(colors[counter]);
}
});
}


buttonColored是单击button时要着色的按钮
counter是一个变量,它取0到4之间的所有值,每次单击button时递增,当它为5 时重置为0

相关内容

最新更新