【发布时间】:2019-07-20 04:09:49
【问题描述】:
我试图在一段时间后在单行 textView 上一一显示 ArrayList 内的值。如何在不阻塞主线程的情况下实现这一点?
我已经编写了能够使用 Thread.sleep 执行此操作的代码,但是在运行几秒钟后,活动崩溃了。我使用 For Loop & Thread.sleep 在一段时间后迭代每个 ArrayList 值。
当活动崩溃时,我在运行几秒钟后收到IndexOutOfBondException。
public void errorRepeater() {
Thread t = new Thread() {
@Override
public void run() {
// !isInterrupted()
while (!isInterrupted()) {
for (xz = 0; xz < errorList.size(); xz++) {
try {
Thread.sleep(2000); //1000ms = 1 sec
runOnUiThread(new Runnable() {
@Override
public void run() {
String sErrorList = errorList.get(xz);
String sErrorListOkBox = errorListOkBox.get(xz);
Log.i("MQTT sErrorList", sErrorList);
TextView tvC1HPLP = findViewById(R.id.errormsg);
tvC1HPLP.setText(sErrorList);
TextView tvok = findViewById(R.id.ok);
tvok.setText(sErrorListOkBox);
rl.setBackgroundResource(R.drawable.errorred);
tvC1HPLP.setTextColor(Color.RED);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
};
t.start();
}
textView 应该在 ArrayList 中一一显示值,而不会导致活动崩溃。
【问题讨论】:
-
什么是errorListOkBox?,如果是两个list,大小不一样
-
errorListOkBox 也是 ArrayList。两个 ArrayList 的大小相同。虽然运行几秒钟后活动崩溃
-
大小不同,这就是问题