如何在 for() 循环中一次将 android 背景颜色设置为多个线性布局?



Android.我正在尝试设置背景颜色以制作某种训练器。但是这个循环一次为所有 4 个 LivearLayout 设置背景颜色 - 在最后一次迭代之后。我需要停顿一下地一一做。我该怎么做?

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 发送广播消息。

最新更新