开发者

(Android) Why won't invalidate() update my buttons immediately?

I have read several forums and examples on using invalidate() in order to update views immediately but I still do not understand why what I am doing will not work. The code below uses image buttons defined by "red", "blue", "green", and "yellow". I set a 1 second delay between each time I try and change a button's appearance. Please someone tell me what i'm d开发者_Python百科oing wrong.

private void showPattern() {
    if (correct == true) {
        for (int k = 0; k < temp_basket.length; k++) {
            if (temp_basket[k] == 0) {
                red.setPressed(true);
                red.invalidate();
                final Handler handler = new Handler();
                Timer t = new Timer();
                t.schedule(new TimerTask() {
                    public void run() {
                        handler.post(new Runnable() {
                            public void run() {
                                red.setPressed(false);
                                red.invalidate();
                            }
                        });
                    }
                }, 1000);

There are 3 more or these blocks after this one that are blue, green, and yellow.


Invaliadate puts a redraw message in the queue

As I see in your code, there are multiple redraws happening on after the other... the OS will try to optimize the rendering by clubbing multiple redraw messages into one (under the condition that there's no other message between them).

What you may want to do is:

private Handler myHandler = new Handler() {
   public void handleMessage(Message msg)
   {
      switch(msg.what) { /* do your work */ }
   }
};

Message msg = Message.obtain(myHandler);
msg.what = <some-number>;
msg.obj = <your-data-to-process>

if(myHandler.containsMessage(<same-number>) {
   myHandler.removeMessages(<same-number>);
}
myHandler.sendMessage(msg);


You can also try using postInvalidate() method, which will cause the invalidate in the UI thread.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜