Well, I guess there is some confusion going on here. You HAVE TO do your GUI updates from the main thread (also called the GUI thread) - otherwise you well get something like "Exception, blabla has leaked a view".
I guess what have misunderstood is that expensive operations, such as networking, should be done in a different thread than the main thread. And if you would like to update the GUI from the network thread you would do as ArtWorkAD says (or his links says).
So for what you want to do, you could achieve with something like replacing your SimpleMotion class with the following:
private class SimpleMotion extends View {
public SimpleMotion(Context context) {
super(context);
new Thread(new Runnable() {
public void run() {
while(true){
try {
Thread.sleep(75);
y++;
postInvalidate();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
@Override protected void onDraw(Canvas canvas) {
float x = canvas.getWidth() / 2;
canvas.drawColor(Color.WHITE);
canvas.drawCircle(x, y, 30, paint);
// if(System.currentTimeMillis() - now > delay) y++;
// invalidate();
}
}
With your old code of having invalidate()
in onDraw()
you would continously be redrawing the gui even while there are no change to it.
The important part of the new code is postInvalidate()
. This makes it possible to tell the GUI thread - from another thread - to redraw the GUI.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…