you should research a little about onDraw()
lifecycle.
onDraw
gets called at the beginning, and then will be called again everytime there is "something" to draw. How you tell a view it has "something" to draw? by calling "invalidate
".
So on your onDraw
you do nothing at first, if the points are not loaded.
When you have finished your calculations, just call invalidate()
and onDraw
will get called later on, asynchronously. By this time, in your OnDraw
you'll detect that your calculations are ready, so then it's when you paint the stuff.
kind of:
boolean myCalculationsAreReady=false;
Paint mPaint=new Paint(); // to draw text "loading" ... (new edit). You have to call mPaint.setColor(Color.WHITE) or any color you want, the default would be Black.
public void onDraw(Canvas canvas) {
if (myCalculationsAreReady) {
drawMyStuff (canvas);
} else {
// You don't have your calculations yet , just ignore, or paint a message ...
drawDataNotReady(canvas);
}
}
private void drawMyStuff (Canvas c) {
// here you have your calculations available
// time to draw !
}
// to make this view totally independent, you can create yourself a progress indicator here.
// you can also put a standard progressbar at the parent level and notify the parent when
// to show / hide it. I like this approach, because it's more efficient (you save one view)
// but obviously you can use any fancy view you like over this one.
private void drawDataNotReady (Canvas c) {
c.drawText (0, c.getHeight() / 2, "Please wait while data is loading ...", mPaint);
}
private void do_my_heavy_calculations () {
// do all your calculations.
.
.
.
// when you are done:
myCalculationsAreReady=true;
invalidate(); // this will call onDraw
}
When you understand how this works, and if your calculations are heavy, you definitely want to take them out of the UI thread. You can use a normal thread just like you ask, but then, the way to call "invalidate" is different:
view.postInvalidate();
this is used to invalidate views from outside the main UI thread (ie. your thread).
Also check out AsyncTask
as a class to help writing asynchronous threads.