我必须制作一个Android内存游戏,屏幕上会显示一系列颜色,然后你必须点击出现的颜色。要显示颜色序列,我只需使用不可更改的按钮来改变颜色。我目前正在使用runOnUiThread的线程执行此操作,但每次只将按钮更改为我想要的最后一种颜色。为什么它不会改变以前的颜色?
final ArrayList<Integer> colours = new ArrayList<Integer>();
Button buttonOne = (Button) findViewById(R.id.colourOne);
Button buttonTwo = (Button) findViewById(R.id.colourTwo);
Button buttonThree = (Button) findViewById(R.id.colourThree);
Button buttonFour = (Button) findViewById(R.id.colourFour);
ColorDrawable buttonOneColor = (ColorDrawable) buttonOne.getBackground();
ColorDrawable buttonTwoColor = (ColorDrawable) buttonTwo.getBackground();
ColorDrawable buttonThreeColor = (ColorDrawable) buttonThree.getBackground();
ColorDrawable buttonFourColor = (ColorDrawable) buttonFour.getBackground();
int one = buttonOneColor.getColor();
int two = buttonTwoColor.getColor();
int three = buttonThreeColor.getColor();
int four = buttonFourColor.getColor();
colours.add(one);
colours.add(two);
colours.add(three);
colours.add(four);
runOnUiThread(new Runnable() {
@Override
public void run() {
for(int x = 0; x < colours.size(); x++) {
try {
Button light = (Button) findViewById((R.id.light));
light.setBackgroundColor(colours.get(x));
Thread.sleep(1000);
} catch (Exception e) {
System.out.println(e);
}
}
}
});
线程在每个setBackground颜色之后处于休眠状态,但按钮颜色实际上不会改变,直到循环到达其最后一个循环。
答案 0 :(得分:1)
你必须在线程调用Thread
上创建一个新的runOnUiThread
并更改颜色。你还必须从Thread中初始化按钮。您必须从x
方法
onCreate
new Thread(new Runnable() {
@Override
public void run() {
for(x = 0; x < colours.size(); x++) {
runOnUiThread(new Runnable() {
@Override
public void run() {
light.setBackgroundColor(colours.get(x));
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();