2013-04-05 104 views
1

我是Java編程的新手,並且有一個問題。 我創建了這段代碼,現在我想插入一個while循環,以便文本每五秒再更改一次。 我試圖插入while語句和Thread.sleep,但它不起作用。如何使用TimerTask的while循環

Timer tim = new Timer(); 

    String rndStr1 = myStringArray[new Random().nextInt(myStringArray.length)]; 
    txtV1.setText(rndStr1); 


    tim.scheduleAtFixedRate(new TimerTask() { 

      @Override 
       public void run() { 
        count++; 

        runOnUiThread(new Runnable() 
        { 

         public void run() 

         {        
         if(count==5)//change the text after 5 seconds 
         { 

         String rndStr1 = myStringArray[new Random().nextInt(myStringArray.length)]; 
         txtV1.setText(rndStr1); 
         } 
      }, 1000, 1000); 
+0

[歡迎使用StackOverflow!](http://stackoverflow.com/faq)如果您能更具體地瞭解爲什麼它不起作用,那麼對於我們想要幫助您解決問題的人員會非常有幫助。你期望會發生什麼?反而發生了什麼? – 2013-04-05 23:00:00

回答

0

嘗試 公共無效的run()

    {        
        if(count==5)//change the text after 5 seconds 
        { 
         wait(5000); 
        String rndStr1 = myStringArray[new Random().nextInt(myStringArray.length)]; 
        txtV1.setText(rndStr1); 
        } 
+0

我不需要使用while(true)表達式,因爲我想每五秒更改一次文本不僅兩次 – Mques 2013-04-05 22:45:11

+0

是否正在調用運行?在這種情況下,你不需要while語句,線程將等待5秒,並設置每隔一個時間的文本... – amitsalyan 2013-04-05 22:45:31

+0

我不這麼認爲 – Mques 2013-04-05 22:46:12

0

爲什麼需要一個while循環?如果您希望文本每5秒更改一次,只需將計時器任務參數設置爲5000,5000而不是1000,1000。根本不需要if(count == 5)。計時器每5秒運行一次,你只需將TextText設置爲textView。那裏有什麼問題?