【发布时间】:2012-02-22 19:46:22
【问题描述】:
我有一个想要倒计时的 TextView(3...2...1...发生了一些事情)。
为了让它更有趣一点,我希望每个数字一开始都是完全不透明的,然后逐渐变透明。
有简单的方法吗?
【问题讨论】:
标签: android animation text textview zebra-striping
我有一个想要倒计时的 TextView(3...2...1...发生了一些事情)。
为了让它更有趣一点,我希望每个数字一开始都是完全不透明的,然后逐渐变透明。
有简单的方法吗?
【问题讨论】:
标签: android animation text textview zebra-striping
试试这样的:
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);
}
我只是打出来的,所以它可能无法按原样编译。
【讨论】:
tv.setText(String.valueOf(count)); 替换tv.setText(count); 代码工作正常
我为此使用了更传统的 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 类,它使用了Handler 和postDelayed 函数。默认情况下,它使用 alpha 动画,但您可以设置任何动画。您可以下载项目here。
【讨论】: