2012-12-14 119 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);