How to set timer in android?

后端 未结 21 939
渐次进展
渐次进展 2020-11-22 00:51

Can someone give a simple example of updating a textfield every second or so?

I want to make a flying ball and need to calculate/update the ball coordinates every se

21条回答
  •  后悔当初
    2020-11-22 01:24

    For those who can't rely on Chronometer, I made a utility class out of one of the suggestions:

    public class TimerTextHelper implements Runnable {
       private final Handler handler = new Handler();
       private final TextView textView;
       private volatile long startTime;
       private volatile long elapsedTime;
    
       public TimerTextHelper(TextView textView) {
           this.textView = textView;
       }
    
       @Override
       public void run() {
           long millis = System.currentTimeMillis() - startTime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds = seconds % 60;
    
           textView.setText(String.format("%d:%02d", minutes, seconds));
    
           if (elapsedTime == -1) {
               handler.postDelayed(this, 500);
           }
       }
    
       public void start() {
           this.startTime = System.currentTimeMillis();
           this.elapsedTime = -1;
           handler.post(this);
       }
    
       public void stop() {
           this.elapsedTime = System.currentTimeMillis() - startTime;
           handler.removeCallbacks(this);
       }
    
       public long getElapsedTime() {
           return elapsedTime;
       }
     }
    

    to use..just do:

     TimerTextHelper timerTextHelper = new TimerTextHelper(textView);
     timerTextHelper.start();
    

    .....

     timerTextHelper.stop();
     long elapsedTime = timerTextHelper.getElapsedTime();
    

提交回复
热议问题