Ответ 1
Использование следующего кода может быть хорошим началом для вас:
public class BackgroundPainter {
private static final int MIN = 800;
private static final int MAX = 1500;
private final Random random;
public BackgroundPainter() {
random = new Random();
}
public void animate(@NonNull final View target, @ColorInt final int color1,
@ColorInt final int color2) {
final ValueAnimator valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(), color1, color2);
valueAnimator.setDuration(randInt(MIN, MAX));
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator animation) {
target.setBackgroundColor((int) animation.getAnimatedValue());
}
});
valueAnimator.addListener(new AnimatorListenerAdapter() {
@Override public void onAnimationEnd(Animator animation) {
//reverse animation
animate(target, color2, color1);
}
});
valueAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
valueAnimator.start();
}
private int randInt(int min, int max) {
return random.nextInt((max - min) + 1) + min;
}
}
С использованием:
final View targetView = findViewById(R.id.root_view);
BackgroundPainter backgroundPainter = new BackgroundPainter();
int color1 = ContextCompat.getColor(this, R.color.colorAccent);
int color2 = ContextCompat.getColor(this, R.color.colorPrimary);
backgroundPainter.animate(targetView, color1, color2);
Обновление
Для изменения фона, состоящего из более чем одного цвета, обычно говорящего о drawables вместо ValueAnimator
, вы можете попробовать использовать нижеприведенное решение.
Я тестировал этот код на устройстве с API 19 и 23.
Определите цвета в colors.xml
:
<color name="color1">#9C27B0</color>
<color name="color2">#FF4081</color>
<color name="color3">#7B1FA2</color>
<color name="color4">#F8BBD0</color>
<color name="color5">#FF5252</color>
<color name="color6">#607D8B</color>
<color name="color7">#FF5722</color>
<color name="color8">#FFA000</color>
Определите градиенты в drawable
:
gradient_1.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="45"
android:endColor="@color/color2"
android:startColor="@color/color1"
android:type="linear"/>
</shape>
gradient_2.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="-45"
android:endColor="@color/color5"
android:startColor="@color/color3"
android:type="linear"/>
</shape>
gradient_3.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:angle="45"
android:endColor="@color/color8"
android:startColor="@color/color7"
android:type="linear"/>
</shape>
Создайте класс GradientBackgroundPainter
в вашем проекте:
public class GradientBackgroundPainter {
private static final int MIN = 4000;
private static final int MAX = 5000;
private final Random random;
private final Handler handler;
private final View target;
private final int[] drawables;
private final Context context;
public GradientBackgroundPainter(@NonNull View target, int[] drawables) {
this.target = target;
this.drawables = drawables;
random = new Random();
handler = new Handler();
context = target.getContext().getApplicationContext();
}
private void animate(final int firstDrawable, int secondDrawable, final int duration) {
if (secondDrawable >= drawables.length) {
secondDrawable = 0;
}
final Drawable first = ContextCompat.getDrawable(context, drawables[firstDrawable]);
final Drawable second = ContextCompat.getDrawable(context, drawables[secondDrawable]);
final TransitionDrawable transitionDrawable =
new TransitionDrawable(new Drawable[] { first, second });
target.setBackgroundDrawable(transitionDrawable);
transitionDrawable.setCrossFadeEnabled(false);
transitionDrawable.startTransition(duration);
final int localSecondDrawable = secondDrawable;
handler.postDelayed(new Runnable() {
@Override public void run() {
animate(localSecondDrawable, localSecondDrawable + 1, randInt(MIN, MAX));
}
}, duration);
}
public void start() {
final int duration = randInt(MIN, MAX);
animate(0, 1, duration);
}
public void stop() {
handler.removeCallbacksAndMessages(null);
}
private int randInt(int min, int max) {
return random.nextInt((max - min) + 1) + min;
}
}
И использование:
public class MainActivity extends AppCompatActivity {
private GradientBackgroundPainter gradientBackgroundPainter;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View backgroundImage = findViewById(R.id.root_view);
final int[] drawables = new int[3];
drawables[0] = R.drawable.gradient_1;
drawables[1] = R.drawable.gradient_2;
drawables[2] = R.drawable.gradient_3;
gradientBackgroundPainter = new GradientBackgroundPainter(backgroundImage, drawables);
gradientBackgroundPainter.start();
}
@Override protected void onDestroy() {
super.onDestroy();
gradientBackgroundPainter.stop();
}
}