Baggio Baggio - 1 month ago 29
Android Question

Android change background image with fade in/out animation

I wrote code which can change background image random every 5 second.now i want to use fade in/out animation to change background image,but I do not know how I can use this animation
this is a my source

void handlechange() {

Handler hand = new Handler();
hand.postDelayed(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub

// change image here
change();

}

private void change() {
// TODO Auto-generated method stub

Random rand = new Random();

int index = rand.nextInt(image_rundow.length);

mapimg.setBackgroundResource(image_rundow[index]);

handlechange();
}
}, 4000);

}


at the moment everythink is ok.I can change background image random,but I do not know how I can use animation fade in/out
If anyone knows solution please help me
thanks

Answer

You need to call these codes.

First, you have to make two xml files for fade in & out animation like this.

fade_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:fillAfter="true"
        android:duration="2000"
        />
</set>

fade_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.0"
        android:fillAfter="true"
        android:duration="2000"
        />
</set>

Second, you have to run animation of imageView like below and also you have to set AnimationListener to change fadeout when fadein finish.

Animation fadeIn = AnimationUtils.loadAnimation(YourActivity.this, R.anim.fade_in);
imageView.startAnimation(fadeIn);

fadeIn.setAnimationListener(new Animation.AnimationListener() {
      @Override
      public void onAnimationStart(Animation animation) {
      }
      @Override
      public void onAnimationEnd(Animation animation) {
          Animation fadeOut = AnimationUtils.loadAnimation(YourActivity.this, R.anim.fade_out);
          imageView.startAnimation(fadeOut);
      }
      @Override
      public void onAnimationRepeat(Animation animation) {
      }
});