How to set timer in android?

后端 未结 21 1508
渐次进展
渐次进展 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

    It is simple! You create new timer.

    Timer timer = new Timer();
    

    Then you extend the timer task

    class UpdateBallTask extends TimerTask {
       Ball myBall;
    
       public void run() {
           //calculate the new position of myBall
       }
    }
    

    And then add the new task to the Timer with some update interval

    final int FPS = 40;
    TimerTask updateBall = new UpdateBallTask();
    timer.scheduleAtFixedRate(updateBall, 0, 1000/FPS);
    

    Disclaimer: This is not the ideal solution. This is solution using the Timer class (as asked by OP). In Android SDK, it is recommended to use the Handler class (there is example in the accepted answer).

提交回复
热议问题