[英]Is there any way to make a ArrayList of TextView from one TextView defined in xml?
[英]Display values in ArrayList one by one in 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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.