开发者

Acceptable method for calling View.invalidate on a repeating timer

I'm planning to have UI elements in constant movement in a View. I'm thinking the best way is to just have a Timer running in the View and calling a method for updating the state of m开发者_Python百科y objects and calling invalidate.

What are the best objects to do this with (Timer, TimerTask, Handler) and what are the best performing ways to do it. Are there any pitfalls I need to avoid for performance?

Also, what is an acceptable amount of time between iterations? Is there a standard, or does it depend on the complexity and amount of objects being drawn?


If you are updating UI Elements, better use View's postDelayed() or postInvalidateDelayed() methods. They guaranteed it will be scheduled in UI thread and redraw.

Iteration isn't too matters. I once made a 'stop-watch' timer that running like 40+ fps and still the UI is responsive enough. Notice that whatever runnable you placed in postDelay will be running on UI's thread, so, if you need to do some heavy drawing, I would prepare (in second thread) it in a separate Bitmap and just post the bitmap whenever the drawing is completed (double buffering technique)

=Update= What I previously done is, I need to draw something on a view, which the whole drawing take about 200ms to complete. The way I do is like this (suppose the run is in a separate thread other than UI thread):

Bitmap result;
void run(){
    while(running){
        result = doTheHeavyWeightDrawing();
        post(new Runnable(){
            setBackgroundDrawable(new BitmapDrawable(...));
        });
        try{
            sleep(100);
        }catch(InterruptedException e){ return; }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜