Java 在线程中的'for'内执行操作 @覆盖 公开募捐{ act.rununuithread(新的Runnable(){ @凌驾 公开募捐{ 对于(int i=0;i
我有一个数字列表,从1到4。我想根据列表中的数字来描绘ImageView,但我需要一系列颜色,因此我需要(例如)在等待1,75秒后显示红色,然后显示绿色等等,但它不起作用!我该怎么办?对于此类任务,线程不是最佳选择。我建议您使用View.postdayed方法。所以你应该得到这样的东西Java 在线程中的'for'内执行操作 @覆盖 公开募捐{ act.rununuithread(新的Runnable(){ @凌驾 公开募捐{ 对于(int i=0;i,java,android,Java,Android,我有一个数字列表,从1到4。我想根据列表中的数字来描绘ImageView,但我需要一系列颜色,因此我需要(例如)在等待1,75秒后显示红色,然后显示绿色等等,但它不起作用!我该怎么办?对于此类任务,线程不是最佳选择。我建议您使用View.postdayed方法。所以你应该得到这样的东西 @Override public void run() { act.runOnUiThread(new Runnable() { @Override
@Override
public void run() {
act.runOnUiThread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < randomNumber.size(); i++) {
Log.d("N",randomNumber.get(i).toString());
if (randomNumber.get(i).intValue() == 1) imgColor.setBackgroundColor(Color.RED);
if (randomNumber.get(i).intValue() == 2) imgColor.setBackgroundColor(Color.GREEN);
if (randomNumber.get(i).intValue() == 3) imgColor.setBackgroundColor(Color.BLUE);
if (randomNumber.get(i).intValue() == 4) imgColor.setBackgroundColor(Color.YELLOW);
try {
Thread.sleep(1750);
} catch (Exception e) {
Thread.currentThread().interrupt();
}
imgColor.setBackgroundColor(Color.BLACK);
try {
Thread.sleep(400);
} catch (Exception e) {
Thread.currentThread().interrupt();
}
}
Toast.makeText(act, "Ripeti la sequenza", Toast.LENGTH_SHORT).show();
}
});
}
我有一个数字列表,从1到4。我想根据列表中的数字绘制ImageView,但我需要一系列颜色,因此我需要(例如)显示红色,等待1,75秒后,显示绿色,等等…您需要稍微澄清一下您的问题。提供适当的上下文,如此代码将在何处运行(活动、片段、异步任务内部等)。你想用什么类型的元素实现什么,等等?“但它不起作用!”使用过度,但对任何试图帮助你的人来说都是无用的。这是一个错误吗?它做的事情是否超出了你的预期?如果是的话,你在做什么?你期望得到什么?这是你应该在问题中解释的。我们不了解你的想法。请永远不要睡眠的UI线程,这将阻止整个用户界面的问题。。。我怎样才能离开这个圈子?我试过回报;但这不起作用,如果你需要停下来,就不要打postDelayed。
void setRandomColor(){
if(!hasRandomColor())
return;
imgColor.setBackgroundColor(getRandomColor());
imgColor.postDelayed(new Runnable(){
void run(){
setRandomColor();
}
}, 1750); // update color again after 1.75 sec
}
...
setRandomColor();