简体   繁体   English

暂停Java GUI中的执行

[英]Pause execution in Java GUI

I am writing a quiz program for the Android (written in Java). 我正在为Android(用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. 当用户回答问题时(单击按钮),我想在屏幕上闪烁一条消息,指出它们是否正确,然后暂停5秒钟,然后继续下一个问题。

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. 您将需要一个AsyncTask Google gives you an intro to it here . Google 在这里向您介绍了它。

When you Thread.sleep() on the main Activity, you are putting the application to sleep. 当您在主Activity上执行Thread.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. AsyncTask将允许您暂停5秒钟,也许会显示一个In Progress进度条,然后从那里开始,而不会冻结屏幕。

Imo AsyncTask is too much for this usecase. Imo AsyncTask在此用例中太多了。

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. 使用处理程序 :您可以发送具有5000毫秒延迟的消息,禁用按钮,当消息到达时,您可以重新启用按钮。 See http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html for more info. 有关更多信息,请参见http://www.tutorialforandroid.com/2009/01/using-handler-in-android.html

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. 免责声明:我只在Java中使用计时器来执行类似的操作,但是我确定它可以在Android中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM