[英]How to set in android background color to several linearlayouts at time in for() loop?
安卓。 我正在尝试设置背景颜色以制作某种培训师。 但是这个循环一次为所有 4 个 LivearLayouts 设置背景颜色 - 在最后一次迭代之后。 我需要一个接一个地完成。 我该怎么做?
private LinearLayout[] lls;
lls = new LinearLayout[4];
lls[0] = findViewById(R.id.ll01);
lls[1] = findViewById(R.id.ll02);
lls[2] = findViewById(R.id.ll03);
lls[3] = findViewById(R.id.ll04);
public void onClick(View view) throws InterruptedException {
for (int i = 0; i < 4; i++) {
Thread.sleep(3000);
lls[i].setBackgroundColor(Color.parseColor("red"));
}
}
这样的代码会在第 4 次迭代结束后立即更改所有 4 个对象的颜色。 在此之前,颜色都没有变化。
我认为您应该使用处理程序而不是 for 循环。 处理程序更便于延迟和做一些事情。 我正在为您放置一些编辑过的代码。
private LinearLayout[] lls;
private Long timeInMillis = 3000L;
private Handler handler;
private Runnable runnable;
private int index = 0;
private void setColors(){
lls = new LinearLayout[4];
lls[0] = findViewById(R.id.ll01);
lls[1] = findViewById(R.id.ll02);
lls[2] = findViewById(R.id.ll03);
lls[3] = findViewById(R.id.ll04);
handler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
if(index!=lls.length){
lls[index++].setBackgroundColor(Color.parseColor("red"));
handler.postDelayed(runnable,timeInMillis);
}
}
};
handler.postDelayed(runnable,timeInMillis);
}
这是错误的代码。 您不能在一个线程中更改活动中的 smth。 通过在 MainActivity 中为 BroadcastReciever 发送广播消息的循环添加线程解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.