背景:制作一个类似于支付宝 财产金额动态增加的效果
思路一:将目标金额等分,利用Handler不断发生消息,延时修改金额。
实习方法:CounterText extends Text 在设置目标值时开始动态展示。
实现代码如下
public class CounterText extends TextView {
//目标金额
private double mGolValue;
//增长过程中的当前金额
private double mCurValue;
//增加比例
private double mRate;
//增加模式
private int rate = 1;
//是否在刷新
private boolean refreshing;
//显示格式
DecimalFormat fnum = new DecimalFormat(",##0.00");
//用于处理增加TextView的UI Handler
private Handler handler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case 0:
if(rate*mCurValue < mGolValue){
setText(fnum.format(mCurValue));
mCurValue += mRate*rate;
//每延时50ms刷新一次
handler.sendEmptyMessageDelayed(0, 50);
}else{
refreshing = false;
setText(fnum.format(mGolValue));
}
break;
default:
break;
}
}
};
public CounterText(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CounterText(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CounterText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public void StartDisplay(){
if(refreshing)
handler.sendEmptyMessage(0);
}
//输入金额和设置 mCurValue mGolValue mRate refreshing等值
public void setValue(String amount) {
double value = Double.parseDouble(amount.replaceAll(",", ""));
if(value > 0.00){
refreshing =true;
mCurValue = 0.00;
mGolValue = value;
mRate = new BigDecimal((double)(value/13.00)).setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
StartDisplay();
}else if(value == 0.00){
refreshing = false;
setText("0.00");
}
}
}
思路二:利用ValueAnimation的UpdateListener回调来动态修改金额。
实习方法:CounterText extends Text 在设置目标值时开始动态展示。
关键代码
private void startAnimation() {
anim = ValueAnimator.ofFloat(0,1);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mCurValue = mGolValue * (float)animation.getAnimatedValue();
invalidate();
}
});
anim.setDuration(500);
anim.start();
startAnim = false;
}