在CodeReview上发布此问题,但没有得到太多回应。链接到代码审核link
我为Android应用创建了一个加载器动画:一个简单的3点加载器。
它正在发挥作用。但这是使用TimerTask进行动画制作的正确方法吗?
public class ThreeDotsLoader extends View {
Paint dot1;
Paint dot2;
Paint dot3;
int defaultColor;
int highlightColor;
boolean animationStarted = false;
TimerTask task;
Timer timer;
int count = 1;
public ThreeDotsLoader(Context context, AttributeSet attrs) {
super(context, attrs);
defaultColor = Color.rgb(44, 78, 82);
highlightColor = Color.WHITE;
initPaint();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Log.d("custom", "ondraw");
canvas.drawCircle(50, 50, 15, dot1);
canvas.drawCircle(100, 50, 15, dot2);
canvas.drawCircle(150, 50, 15, dot3);
}
private void initPaint(){
dot1 = new Paint();
dot1.setColor(defaultColor);
dot1.setStyle(Paint.Style.FILL);
dot1.setAntiAlias(true);
dot2 = new Paint();
dot2.setColor(defaultColor);
dot2.setStyle(Paint.Style.FILL);
dot2.setAntiAlias(true);
dot3 = new Paint();
dot3.setColor(defaultColor);
dot3.setStyle(Paint.Style.FILL);
dot3.setAntiAlias(true);
}
public void startLoading(){
task = new TimerTask() {
@Override
public void run() {
switch(count){
case 1:
dot1.setColor(highlightColor);
dot2.setColor(defaultColor);
dot3.setColor(defaultColor);
count++;
break;
case 2:
dot1.setColor(defaultColor);
dot2.setColor(highlightColor);
dot3.setColor(defaultColor);
count++;
break;
case 3:
dot1.setColor(defaultColor);
dot2.setColor(defaultColor);
dot3.setColor(highlightColor);
count = 1;
break;
}
animationStarted = true;
postInvalidate();
}
};
timer = new Timer();
timer.schedule(task, 0, 300);
}
public void stopLoading(){
animationStarted = false;
timer.cancel();
}
}
答案 0 :(得分:1)
我建议Handler使用advantages
While rescheduling Handler is very easy, you can not reschedule Timer
In Handler you can attach to any Runnable but Timer schedule for only one TimerTask
TimerTask is purely background task so you can not update UserInterface, but that's not true for Handler's Runnables