简体   繁体   中英

ValueAnimator working with Button but not with LinearLayout

The following code is working when the supplied view is a Button but when it's a LinearLayout nothing happens (Background color doesn't change).

If I manually set the color on the LinearLayout without the ValueAnimator it works. I also tried using a ObjectAnimator but the result looked terrible.

An example call:

playBlinkAnimation(view, activity.getResources().getColor(R.color.transparent), activity.getResources().getColor(R.color.colorRed), 5000);


view.getBackground().setColorFilter(activity.getResources().getColor(R.color.colorRed), PorterDuff.Mode.DARKEN);


private void playBlinkAnimation(final View view, int colorFrom, int colorTo, int duration) {

        ValueAnimator colorAnimation = new ValueAnimator();
        colorAnimation.setIntValues(colorFrom, colorTo);
        colorAnimation.setEvaluator(new ArgbEvaluator());


        colorAnimation.setDuration(duration);
        colorAnimation.setRepeatCount(ValueAnimator.INFINITE);
        colorAnimation.setRepeatMode(ValueAnimator.REVERSE);

        colorAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animator) {
                view.getBackground().setColorFilter((int) animator.getAnimatedValue(), PorterDuff.Mode.DARKEN);
            }

        });

        colorAnimation.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                view.getBackground().setColorFilter(null);
            }

            @Override
            public void onAnimationCancel(Animator animation) {
                view.getBackground().setColorFilter(null);
                view.setAlpha(1);
                view.getBackground().setColorFilter(null);
            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        colorAnimation.start();
    }

You can try using AnimatorSet and it's playTogether function. It takes an array of Animators, and it's designed to run multiple animations together, but it should work with only one animation as well.

Hope that helps you!

Since you seem to want your layout to transition from transparent background to opaque red, you should animate the layout's alpha parameter

ObjectAnimator animator = ObjectAnimator.ofInt(view, "alpha", 0, 1);
animator.setDuration(5000);
animator.setInterpolator(new LinearInterpolator());
animator.start();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM