我有一个我想倒计时的 TextView(3...2...1...发生了一些事情)。
为了让它更有趣一点,我希望每个数字都以完全不透明开始,然后逐渐变透明。
有没有一种简单的方法可以做到这一点?
我有一个我想倒计时的 TextView(3...2...1...发生了一些事情)。
为了让它更有趣一点,我希望每个数字都以完全不透明开始,然后逐渐变透明。
有没有一种简单的方法可以做到这一点?
尝试这样的事情:
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);
}
我只是打出来的,所以它可能无法按原样编译。
为此,我使用了更传统的 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();
您可以使用0
和count
值来使计数器从任意数字变为任意数字,并使用1000
来设置整个动画的持续时间。
请注意,这支持 Android API 级别 11 及更高版本,但您可以使用出色的Nineoldandroids项目使其轻松向后兼容。
我首先尝试了@dmon 解决方案,但是由于每个动画都从前一个动画的末尾开始,因此在几次调用后最终会出现延迟。
所以,我实现CountDownAnimation
了使用 aHandler
和postDelayed
函数的类。默认情况下,它使用 alpha 动画,但您可以设置任何动画。您可以在此处下载该项目。