下面是一个使用淡入淡出动画更改RelativeLayout背景图像的示例代码:
import android.animation.ObjectAnimator;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.RelativeLayout;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private RelativeLayout mainLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainLayout = findViewById(R.id.main_layout);
// 设置初始背景图像
Drawable initialDrawable = getResources().getDrawable(R.drawable.background_image);
mainLayout.setBackground(initialDrawable);
// 创建淡入淡出动画
Animation fadeIn = new AlphaAnimation(0, 1);
fadeIn.setDuration(1000);
Animation fadeOut = new AlphaAnimation(1, 0);
fadeOut.setDuration(1000);
fadeOut.setStartOffset(1000); // 淡出动画开始前的延迟时间
// 设置动画监听器
fadeOut.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// 当淡出动画开始时,更改背景图像
Drawable newDrawable = getResources().getDrawable(R.drawable.new_background_image);
mainLayout.setBackground(newDrawable);
}
@Override
public void onAnimationEnd(Animation animation) {
// 动画结束时清除动画
mainLayout.clearAnimation();
}
@Override
public void onAnimationRepeat(Animation animation) {
// 不需要实现
}
});
// 应用淡入淡出动画
mainLayout.startAnimation(fadeIn);
mainLayout.startAnimation(fadeOut);
}
}
上面的代码会将RelativeLayout
的背景图像从background_image
淡出,并在淡出动画开始时更改为new_background_image
。