我有两个类MyView和MyThread,并希望每隔几毫秒从MyThread类中的一个计时器重新绘制视图。 计时器开始运行,但我的视图不会重新绘制,我不明白为什么。这是我的代码:
MyView的:
public class MyView extends SurfaceView{
private MainActivity mainActivity;
private Random random = new Random();
public MyView(Context context) {
super(context);
mainActivity = (MainActivity)context;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
setBackgroundColor(Color.argb(random.nextInt(255),random.nextInt(255),
random.nextInt(255),random.nextInt(255)));
}
}
MyThread的:
public class MyThread implements SurfaceHolder.Callback {
private Timer timer = new Timer();
private MainActivity mainActivity;
private MyView myView;
public MyThread(Context context) {
mainActivity = (MainActivity) context;
myView = new MyView(context);
timer.schedule(new TimerThread(),50,50);
}
class TimerThread extends TimerTask {
@Override
public void run() {
mainActivity.runOnUiThread(new TimerTask() {
@Override
public void run() {
Log.v("Log","Timer run");
myView.setBackgroundColor(Color.RED);
myView.invalidate();
}
});
}
}
任何帮助都将不胜感激。