Text color animation

前端 未结 8 1855
南旧
南旧 2020-12-14 10:09

Is there a way to animate a text color change (from anycolor to white)?

The only variant I came up with, is placing two textviews (with the same text) in one place,

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-14 10:43

    As others mention, using ObjectAnimator solves for this. However, in the existing posts - I wasn't seeing how to set duration. For me the color change would happen immediately.

    The solution below shows:

    1. setting the animation with some interval; thanks to post: https://plus.google.com/+CyrilMottier/posts/X4yoNHHszwq

    2. a way to continuously cycle back and forth between the 2 colors


    void animateTextViewColors(TextView textView, Integer colorTo) {
    
        final Property property = new Property(int.class, "textColor") {
            @Override
            public Integer get(TextView object) {
                return object.getCurrentTextColor();
            }
    
            @Override
            public void set(TextView object, Integer value) {
                object.setTextColor(value);
            }
        };
    
        final ObjectAnimator animator = ObjectAnimator.ofInt(textView, property, colorTo);
        animator.setDuration(8533L);
        animator.setEvaluator(new ArgbEvaluator());
        animator.setInterpolator(new DecelerateInterpolator(2));
        animator.start();
    }
    
    void oscillateDemo(final TextView textView) {
    
        final int whiteColor = ContextCompat.getColor(TheApp.getAppContext(), R.color.white);
        final int yellowColor = ContextCompat.getColor(TheApp.getAppContext(), R.color.yellow);
    
        final int counter = 100;
    
        Thread oscillateThread = new Thread() {
            @Override
            public void run() {
    
                for (int i = 0; i < counter; i++) {
    
                    final int fadeToColor = (i % 2 == 0)
                            ? yellowColor
                            : whiteColor;
    
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
    
                            animateTextViewColors(textView, fadeToColor);
                        }
                    });                                      
    
                    try {
                        Thread.sleep(2450);
                    }
                    catch (InterruptedException iEx) {}
                }
            }
        };
    
        oscillateThread.start();
    }
    

提交回复
热议问题