Mac Ryze Mac Ryze - 13 days ago 5
Java Question

How to make each ImageView of list to start animation one by one?

I'm new to Android and I have 9

ImageView
s that I want to make transparent. I'm using
AlphaAnimation
to make them fade. They fade indeed but I want to make them fade one by one. Unfortunately they all fade together and I don't know why.
I tried to use various ways to do it(including
CountDownTimer
,
Thread.sleep()
,
new Handler().postDelayed()
), but there is no change. All of the ImageViews fade simultaneously, not one by one. I know they are capable of doing it because animation on one works, but iteration throught list of this views ends up with all of them being animated at the same time.

Important methods(I guess):

private void fadeImageTiles(List<ImageView> ivs) {
Collections.shuffle(ivs);

for (ImageView iv : ivs) {
//maybe there's problem with iteration?
gradientFade(iv);
}
}

private void gradientFade(ImageView iv){
AlphaAnimation animation = new AlphaAnimation(1f,0f);
animation.setDuration(2000);
iv.startAnimation(animation);
iv.setVisibility(View.INVISIBLE);
}


Final effect is to make them fade randomly revealing image behind

Answer

You can use void setStartOffset (long startOffset) to specify after how many milliseconds the view should be animated. For example:

private void fadeImageTiles(List<ImageView> ivs) {
    Collections.shuffle(ivs);

    for (int i = 0; i < ivs.size(); i++) {
      //maybe there's problem with iteration?
        gradientFade(ivs.get(i), i);
    }
}

private void gradientFade(ImageView iv, int index){
    AlphaAnimation animation = new AlphaAnimation(1f,0f);
    animation.setDuration(2000);
    animation.setStartOffset(index * 500);
    iv.startAnimation(animation);
    iv.setVisibility(View.INVISIBLE);
}

Or you can use ViewPropertyAnimator without writing much code. Replace your code inside your gradientFade method with this:

iv.animate().alpha(0).setDuration(2000).setStartDelay(index * 500);
Comments