安卓简单文本视图动画

7

我有一个TextView,我想让它倒计时(3...2...1...然后做一些事情)。

为了更有趣,我希望每个数字都从完全不透明开始,并逐渐变为透明。

有没有简单的方法来实现这个效果?

3个回答

14

尝试像这样做:

 private void countDown(final TextView tv, final int count) {
   if (count == 0) { 
     tv.setText(""); //Note: the TextView will be visible again here.
     return;
   } 
   tv.setText(String.valueOf(count));
   AlphaAnimation animation = new AlphaAnimation(1.0f, 0.0f);
   animation.setDuration(1000);
   animation.setAnimationListener(new AnimationListener() {
     public void onAnimationEnd(Animation anim) {
       countDown(tv, count - 1);
     }
     ... //implement the other two methods
   });
   tv.startAnimation(animation);
 }

我刚刚把它打出来,所以可能不能直接编译。


1
将“tv.setText(count);”替换为“tv.setText(String.valueOf(count));”,代码就可以正常工作。 - Menelaos Kotsollaris

4

我为此使用了更传统的Android风格动画:

        ValueAnimator animator = new ValueAnimator();
        animator.setObjectValues(0, count);
        animator.addUpdateListener(new AnimatorUpdateListener() {
            public void onAnimationUpdate(ValueAnimator animation) {
                view.setText(String.valueOf(animation.getAnimatedValue()));
            }
        });
        animator.setEvaluator(new TypeEvaluator<Integer>() {
            public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
                return Math.round((endValue - startValue) * fraction);
            }
        });
        animator.setDuration(1000);
        animator.start();

你可以调整0count的值,使计数器从任何数字到任何数字,并使用1000来设置整个动画的持续时间。
请注意,此功能支持Android API级别11及以上,但您可以使用神奇的nineoldandroids项目轻松实现向后兼容。

2
请看 CountDownAnimation
我首先尝试了@dmon的解决方案,但由于每个动画都从前一个动画结束时开始,因此在多次调用后会出现延迟。
因此,我实现了CountDownAnimation类,它使用了HandlerpostDelayed函数。默认情况下,它使用alpha动画,但您可以设置任何动画。您可以在这里下载该项目。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接