运行中的SetText视图无法正常工作

时间:2012-09-05 01:58:10

标签: android

我想让我的runnable每隔0.75秒更新一次我的UI,我不想使用AsyncTask。但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();
                }
            }

        }
    };

3 个答案:

答案 0 :(得分:1)

由于此行Thread.sleep(750);

,TextView仅设置在for循环的末尾

在将文本设置为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() {         
 }

}开始();

答案 1 :(得分:1)

您不应该从另一个线程调用UI线程。 使用CountDownTimer

    new CountDownTimer(wordSize*750, 750) {

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

         public void onFinish() {

         }
    }.start();

答案 2 :(得分:1)

尝试此操作,当您希望进行操作时调用“doStuff()”

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();
}

希望这有帮助!