Search code examples
androiddelayandroid-handler

How to delay appearance of image with handler postDelayed


I have five textviews. Each one has a badge that has visibility set to gone. I want when I press a button the badges to appear one at a time with a delay of 2 sec bettween each other. This is my actual code for the onClick event:

 public void checkAnswers(View v)
    {
        Handler handler = new Handler(Looper.getMainLooper());
        fadeInAnimation = AnimationUtils.loadAnimation(activity_Trivia.this,   R.anim.fade_in);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                badge1.startAnimation(fadeInAnimation);
                badge1.setVisibility(View.VISIBLE);
            }
        }, 0);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                badge2.startAnimation(fadeInAnimation);
                badge2.setVisibility(View.VISIBLE);
            }
        }, 2000);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                badge3.startAnimation(fadeInAnimation);
                badge3.setVisibility(View.VISIBLE);
            }
        }, 4000);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                badge4.startAnimation(fadeInAnimation);
                badge4.setVisibility(View.VISIBLE);
            }
        }, 6000);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                badge5.startAnimation(fadeInAnimation);
                badge5.setVisibility(View.VISIBLE);
            }
        }, 8000);
    }

The problem is that after the first delay,when the second badge appears, the first badge hides and appears again with the second and so on. I want the first badge,second badge... to stay visible while the next badge appears. Any ideas? I searched but nothing came up. Thank you!


Solution

  • Create a seperate Animation object for every single badge (call AnimationUtils.loadAnimation(...) one time for every single badge).

    This should solve the issue.