Android change background image with fade in/out animation
You can use relativeLayout, and add one layer of background view which set both height and width match_parent. All other UI element should put on top of this view. In your code. Define fadeOut and fadeIn animation. Find that background view by id, then do this:
xxxBackground.startAnimation(fadeOut);
xxxBackground.setBackgroundResource(R.drawable.your_random_pic);
xxxBackground.startAnimation(fadeIn);
You can use some interpolator to tune the performance.
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 fadeOut = AnimationUtils.loadAnimation(YourActivity.this, R.anim.fade_out);
imageView.startAnimation(fadeOut);
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
Animation fadeIn = AnimationUtils.loadAnimation(YourActivity.this, R.anim.fade_in);
imageView.startAnimation(fadeIn);
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
For fade in animation , create new folder named 'anim' in your res folder and inside it, create 'fade_in.xml' with following code
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<alpha
android:duration="@android:integer/config_mediumAnimTime"
android:fromAlpha="0.0"
android:interpolator="@android:anim/decelerate_interpolator"
android:toAlpha="1.0" />
</set>
now to run this animation on your imageview, use following code in your activity
Animation anim = AnimationUtils.loadAnimation(YourActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
for fadeout animation, just swap values of android:fromAlpha and android:toAlpha
Hope this helps.