java - 在textView中一一显示ArrayList中的值
问题描述
我试图在一段时间后在单行 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 中一一显示值,而不会导致活动崩溃。
解决方案
仅供参考,您可以尝试这样的事情。
// You can define those both textview globally.
TextView tvC1HPLP = findViewById(R.id.errormsg);
TextView tvok = findViewById(R.id.ok);
Handler mHandler = new Handler();
final Runnable runnable = new Runnable() {
int count = 0;
@Override
public void run() {
String sErrorList = errorList.get(count%errorList.size);
String sErrorListOkBox = errorListOkBox.get(count%errorListOkBox.size);
tvC1HPLP.setText(sErrorList);
tvok.setText(sErrorListOkBox);
rl.setBackgroundResource(R.drawable.errorred);
tvC1HPLP.setTextColor(Color.RED);
count++;
mHandler.postDelayed(this, 4000); // four second in ms
}
};
mHandler.postDelayed(runnable, 1000);
推荐阅读
- php - 电话号码正则表达式条件
- python - 无法使用flask-socketio在聊天应用程序的HTML页面中显示消息
- node.js - 如何在 Node.Js 中将 Angular 组件渲染为 HTML(发送电子邮件)
- python - 如何解决 AttributeError:'Top2Vec' 对象没有属性 'topic_sizes'?
- macos - 在 macOS 上修复损坏的 Kerberos
- python - Python docxtpl - 如何更改列的大小?
- ios - 对于 IOS - 如何在 Native Base 的输入中垂直居中对齐文本?
- ionic-framework - 离子(V4)离子服务-带有属性显示的白屏:core.css中没有
- python - 大熊猫组内的行之间的差异
- api - 如何保护不需要的恶意请求的公共 API 路由?