1

我希望每 0.75 秒更新一次我的 UI,我不想使用 AnsyTask。但是 TextView 只设置在 for 循环的末尾,知道为什么吗?

...

robotWords = "........Hey hello user!!!";
        wordSize = robotWords.length();
        mHandler.postDelayed(r, 750);
    }

    private Runnable r = new Runnable()
    {
        public void run()
        {
            for(int i=0; i<wordSize; i++)
            {           
                robotTextView.setText("why this words only display on the textView at last operation on this for loop?");
                Log.i(TAG, robotWords.substring(0, i));
                try
                {
                    Thread.sleep(750);
                } catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

        }
    };
4

3 回答 3

1

Try this, call "doStuff()" when you want the operation to take place

public void doStuff() {
    new Thread(new Runnable() {
        public void run() {

    for(int i=0; i<wordSize; i++) {           
        robotTextView.setText("why this words only display on the textView at last operation on this for loop?");
        Log.i(TAG, robotWords.substring(0, i));


                robotTextView.post(new Runnable() {
                    public void run() {
                           robotTextView.setText("why this words only display on the textView at last operation on this for loop?");
                    }
                });

        try {
            Thread.sleep(750);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

            }
        }
    }).start();
}

Hope this helps!

于 2012-09-05T02:34:40.863 回答
1

由于这一行,TextView 仅设置在 for 循环的末尾Thread.sleep(750);

您的线程将在文本真正设置为您的 textview 之前休眠。我认为您应该每 750 毫秒调用一次 Handler.postDelayed 而不是使用 Thread.sleep(750);或使用 CountDownTimer

new CountDownTimer(750 * wordSize, 750) {

 public void onTick(long millisUntilFinished) {
     robotTextView.setText("why this words only display on the textView at last operation on this for loop?");
            Log.i(TAG, robotWords.substring(0, i));
 }

 public void onFinish() {         
 }

}。开始();

于 2012-09-05T02:13:13.830 回答
1

您不应该从另一个线程调用 UI 线程。使用倒计时

    new CountDownTimer(wordSize*750, 750) {

         public void onTick(long millisUntilFinished) {
             robotTextView.setText("...");
         }

         public void onFinish() {

         }
    }.start();
于 2012-09-05T02:15:19.450 回答