开发者

Slowing the GUI down in Android

My Android App works fine, except the end se开发者_StackOverflow社区quence. Its a game and at the end the screen shows the score:

TextView allscores = new TextView(this);

allscores.setText("Your score: "+ mypoints);

Next I want the GUI to slowdown for a few seconds so the user has time to take in the information. Maybe 2 or 3 secs is fine.

try {
                Thread.sleep(3000);

            } catch (InterruptedException e) {

                e.printStackTrace();
            }

                            layout.removeAllViews();

Bear in mind, I'm new to thread programming. All this is done on the UI thread, I have no other threads running. Next I put in a final splash screen ending:

AnView animator = new AnView(this);

            layout.addView(animator);

where AnView is my own extension of View.

All in all it runs great. Problem is the thread sleeps for 3 seconds without showing my final score. I don't know why. I don't know why it doesn't show my final score before sleeping. It actually goes blank, indicating that it removed all views and then slept.


You're not seeing the score because sleeping on the UI thread prevents the layout and drawing operations that make your text changes visible. Never sleep on the UI thread.

Using a new thread for this is overkill. Use a Handler and the postDelayed method to make something happen after a delay.

private final Handler mHandler = new Handler();

Then when you want to do something later,

mHandler.postDelayed(new Runnable() {
    public void run() {
        doDelayedThing();
    }
}, 3000);


As others have pointed out: don't use sleep in the UI thread.

What you should do instead is described here:

http://developer.android.com/guide/appendix/faq/commontasks.html#threading

in section "Handling Expensive Operations in the UI Thread"


It is not recommended to ever sleep the main UI thread. Try something like this:

new Thread(new Runnable(){ //do work here });

Or you could try using a Toast popup for the score.


You can also use Timer to wait 3 seconds, which will start a new thread after the time runs out.

Timer timer = new Timer();
timer.schedule(new TimerTask() {
    @Override
    public void run() {
                AnView animator = new AnView(this);
                layout.addView(animator);
    }
}, 3000);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜