3

可能重复:
每 N 秒更新一次 TextView?

在这里,我想在每次迭代计算后更新 textview 中的 Hr 值,但每次延迟 2 秒。我不知道该怎么做。我现在在 textview 中得到的是迭代的最后一个值。我希望所有值都以恒定延迟显示。任何人都请帮忙。

    for(int y=1;y<p.length;y++)
    {
       if(p[y]!=0)
        {
        r=p[y]-p[y-1];
          double x= r/500;
          Hr=(int) (60/x);
          Thread.sleep(2000);
         settext(string.valueof(Hr));
      }
    }
4

5 回答 5

4
public class MainActivity extends Activity{
protected static final long TIME_DELAY = 5000;
//the default update interval for your text, this is in your hand , just run this sample
TextView mTextView;
Handler handler=new Handler();  
int count =0;
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mTextView=(TextView)findViewById(R.id.textview);
    handler.post(updateTextRunnable);
}


Runnable updateTextRunnable=new Runnable(){  
  public void run() {  
      count++;
      mTextView.setText("getting called " +count);
      handler.postDelayed(this, TIME_DELAY);  
     }  
 };  
}

我希望这次你能进入代码并运行它。

于 2013-01-23T09:53:18.010 回答
2

你应该使用计时器类....

Timer timer = new Timer();
        timer.schedule(new TimerTask() {

        public void run() {


        }, 900 * 1000, 900 * 1000);

上面的代码是每 15 分钟一次。更改此值并在您的情况下使用.....

于 2013-01-23T09:43:16.283 回答
2

使用HandlerorTimerTask(with runOnUiThread())代替 for 循环在每 5 秒后更新文本:

Handler handler=new Handler();  

handler.post(runnable);  
Runnable runnable=new Runnable(){  
  @Override  
    public void run() {  
      settext(string.valueof(Hr));  //<<< update textveiw here
      handler.postDelayed(runnable, 5000);  
     }  
 };  
于 2013-01-23T09:44:02.783 回答
1

TimerTask正是您所需要的。

于 2013-01-23T09:46:11.970 回答
0

让我们只希望它对您有足够的帮助

import java.awt.Toolkit;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class demo 
{
  Toolkit toolkit;
  Timer timer;
  public demo()
  {
    toolkit = Toolkit.getDefaultToolkit();
    timer = new Timer();
    timer.schedule(new scheduleDailyTask(), 0, //initial delay
        2 * 1000); //subsequent rate
  }
  class scheduleDailyTask extends TimerTask 
  {
    public void run() 
    {
      System.out.println("this thread runs for every two second");
      System.out.println("you can call this thread to start in your activity");
      System.out.println("I have used a main method to show demo");
      System.out.println("but you should set the text field values here to be updated simultaneouly");
    }
  }
  public static void main(String args[]) {
    new demo();
  }
}
于 2013-01-23T10:20:38.843 回答