skip to Main Content

Can I animate an increase in a score variable using a textview over 1 second?

2

Answers


  1. Chosen as BEST ANSWER

    Another approach which works well is to use new Handler(Looper.getMainLooper()).postDelayed(new Runnable() ... such as:

    private void wonBlockIncreaseScore() {
            int oldScore = score;
            score = score + 50;
            int timeOverWhichAnimationShouldRun = 1000; //ms
            int equalGap = (timeOverWhichAnimationShouldRun / (score-oldScore));
            //equal gap...
            for (int i = oldScore; i < score; i++) {
                int finalI = i;
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        scoreTextView.setText(String.valueOf(finalI+1));
                    }
                }, (equalGap * i));
            }
    

  2. I would highly recommend using checking out this question, there are various approaches that works differently for different cases.

    You could try:

    //You can animate from a specified starting point till the final score
    val valueAnimator = ValueAnimator.ofInt(initialScore, finalScore)
    
    //Here you set the duration of the animation in milliseconds
    valueAnimator.duration = 1000 
    
    
    valueAnimator.addUpdateListener { valueAnimator -> 
        //The textview gets updates as the value animator's value updates
        textView.text = valueAnimator.animatedValue.toString() 
    
    }
    
    //Here you just start the animation
    valueAnimator.start() 
    

    This could also be repurposed into it’s own method 😉

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search