首页 > 解决方案 > 在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 中一一显示值,而不会导致活动崩溃。

标签: javaandroid

解决方案


仅供参考,您可以尝试这样的事情。

   // 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);

推荐阅读