Reputation: 3666
Basically when a user wins a game I want to animate (counting up) from the original score to the new score.
I'm trying to do this using a timer as shown below
public final void updatePlayerScore(final int newScore){
final Timer t = new Timer();
TimerTask tt = new TimerTask() {
@Override
public void run() {
mHandler.post(new Runnable() {
public void run() {
initialScore++;
// update TextView
scoresTextView.setText("" + initialScore);
if(initialScore >= newScore){
t.cancel();
mHandler2.postDelayed(mLaunchNextQuestion,1000);
}
}
});
}
};
t.scheduleAtFixedRate(tt, 0, 2);
The initial score gets incremented upwards every time the TimerTask is called (every 2 milliseconds) when the initialScore equals or is greater than the newScore - it should cancel the timer and then load a new activity mLaunchNextQuestion.
What is happening in reality is that mLaunchNextQuestion is getting called more than once. I'm guessing this is because either timer.cancel is not working or the timer is running to fast to be cancelled?
UPDATE---
Thanks for the advice on the refresh rate being too quick. I ended up ditching the timer and instead used a runnable that calls itself after a delay.
private Runnable updatePlayerScoreNew(final int newScore){
Runnable aRunnable = new Runnable(){
public void run(){
if (initialScore >= newScore) {
mHandler.postDelayed(mLaunchNextQuestion,1000);
} else {
initialScore+=40;
if(initialScore > newScore){
scoresTextView.setText("" + newScore);
}else{
scoresTextView.setText("" + initialScore);
}
mHandler.postDelayed(updatePlayerScoreNew(newScore), 40);
}
}
};
return aRunnable;
}
Upvotes: 1
Views: 671
Reputation: 31045
Why are you running this timer at 500Hz? This is just displaying a ticking score, right? The human eye cannot see things moving that fast. Actually, it only registers changes at something like 13Hz, (depending on what kind of change it is) so usually, it's safe to double that rate (to 25Hz or 30Hz).
500Hz is excessive, though. Try setting the rate to something slower, and see what happens, then.
You can also try calling cancel() on the TimerTask, too, although I think calling cancel()
on the Timer
should be valid.
Upvotes: 2