2012-12-14 121 views
1

對不起,提出這樣一個基本問題,實際上我需要經過一定的時間間隔後調用一個方法,它實際上是將文本分配給android中的textView,這應該會改變。所以請給我一個最好的方法去做這個。 感謝您的期待。Android -Timer概念

{ 
     int splashTime=3000; 
     int waited = 0; 
     while(waited < splashTime) 
     { 
      try { 
        ds.open(); 
        String quotes=ds.getRandomQuote(); 
        textView.setText(quotes); 
        ds.close(); 


       } 
       catch(Exception e) 
       { 
        e.printStackTrace(); 
       } 
     } 
     waited+=100; 
    } 
+0

有什麼不對的代碼?有沒有錯誤?你有沒有調用threadname.start()? –

回答

4

您考慮過CountDownTimer嗎?比如這樣的事情:

 /** 
    * Anonymous inner class for CountdownTimer 
    */ 
    new CountDownTimer(3000, 1000) { // Convenient timing object that can do certain actions on each tick 

     /** 
     * Handler of each tick. 
     * @param millisUntilFinished - millisecs until the end 
     */ 
     @Override 
     public void onTick(long millisUntilFinished) { 
      // Currently not needed 
     } 

     /** 
     * Listener for CountDownTimer when done. 
     */ 
     @Override 
     public void onFinish() { 
      ds.open(); 
       String quotes=ds.getRandomQuote(); 
       textView.setText(quotes); 
       ds.close(); 
     } 
    }.start(); 

當然,你可以把它放在一個循環中。

1

您可以用定時器像這樣延遲更新您的UI:

long delayInMillis = 3000; // 3s 
    Timer timer = new Timer(); 
    timer.schedule(new TimerTask() { 
     @Override 
     public void run() { 
      // you need to update UI on UIThread 
      runOnUiThread(new Runnable() { 
       @Override 
       public void run() { 
        ds.open(); 
        String quotes=ds.getRandomQuote(); 
        textView.setText(quotes); 
        ds.close(); 
       } 
      }); 
     } 
    }, delayInMillis); 
1

使用處理,並把它放到一個Runnable:

int splashTime = 3000; 
Handler handler = new Handler(activity.getMainLooper()); 
handler.postDelayed(new Runnable() { 
    @Override 
    public void run() { 
     try { 
      ds.open(); 
      String quotes=ds.getRandomQuote(); 
      textView.setText(quotes); 
      ds.close(); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 
}, splashTime);