开发者

Pause execution in Java GUI

开发者 https://www.devze.com 2023-03-14 15:56 出处:网络
I am writing a quiz program for the Android (written in Java). When the user answers a question (by clicking a button), I want to flash a message on the screen saying whether they were correct or not,

I am writing a quiz program for the Android (written in Java). When the user answers a question (by clicking a button), I want to flash a message on the screen saying whether they were correct or not, followed by a 5 second pause before moving on to the next question.

However, when an answer button is clicked, the program pauses, but does not display the message of correct/incorrect. The message only comes up 开发者_运维技巧once the sleep method has finished.

if (correct)   
    Answer.setText("CORRECT!"); 
else 
    Answer.setText("WRONG!"); 

try { Thread.sleep(5000); } 
catch(InterruptedException e) {}

As a bonus, I'd like the answer buttons to be disabled during the pause.


You'll need an AsyncTask for that. Google gives you an intro to it here.

When you Thread.sleep() on the main Activity, you are putting the application to sleep. The AsyncTask will allow you to pause for the 5 seconds, maybe show a little In Progress bar and then pick up from there, without freezing the screen.


Imo AsyncTask is too much for this usecase.

Don't use sleep. Instead set your correct/incorrect message and than do this:

new Handler().postDelayed(new Runnable(){
  public void run()
  {
    goToNextScreen();
  }
}
, 5000);


Use a Handler: you can send a message with a 5000 millisecond delay, disable the buttons and when the message arrives you can re-enable the buttons. See http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html for more info.


You should look into using timers for this. I don't think using threads are sensible for this. Using a timer to move onto the next question would work.

Look at timers here

Hope this helps.

Disclaimer: I have only used timers in Java to do something similar but i'm sure it would work in Android.

0

精彩评论

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

关注公众号