LinearLayout颜色更改(平滑动画)

时间:2018-08-24 18:04:25

标签: android animation colors fade

我有一个带有LinearLayout开头的background(让我们说:#ff4455),并且我希望background的颜色在单击{{1 }}以“平滑方式(FADE)..怎么做..

注意:我有四个按钮,每个按钮会将背景更改为另一种颜色。

1 个答案:

答案 0 :(得分:0)

使用值动画器

int[] colors = new int[]{...} // create an array with colors for each button

button1.setOnClickListener(v -> updateBackgroundColor(0)); 
button2.setOnClickListener(v -> updateBackgroundColor(1)); 
button3.setOnClickListener(v -> updateBackgroundColor(2)); 
button4.setOnClickListener(v -> updateBackgroundColor(3)); 

private void updateBackgroundColor(int buttonPos) {
    Drawable background = view.getBackground();
    if (background instanceof ColorDrawable)
        color = ((ColorDrawable) background).getColor();
    int colorFrom = color == null ? defaultColor : color;
    int colorTo = colors[buttonPos];
    ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
    colorAnimation.setDuration(250); // milliseconds
    colorAnimation.addUpdateListener(new AnimatorUpdateListener() {

        @Override
        public void onAnimationUpdate(ValueAnimator animator) {
            linearLayout.setBackgroundColor((int) animator.getAnimatedValue());
        }
});
colorAnimation.start();
}