public class Main2Activity extends AppCompatActivity {
int square5 = 0;
int flag = 1;
int userclick5 = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//here i set some click listeners. one example is as follows:
ImageButton image_button1 = (ImageButton) findViewById(R.id.image_button1);
image_button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
goToIB();
}
});
}
//click listener call this function. This function set the color of image button as green.
//Then it calls the function goTofirst3cpu()
private int goToIB() {
ImageButton imageButton5 = (ImageButton) findViewById(R.id.image_button5);
if (imageButton5.isPressed() & square5 == 0) {
{
imageButton5.setImageResource(R.color.green_color);
flag = flag + 1;
square5 = square5 + 1;
userclick5 = userclick5 + 1;
goTofirst3cpu();
return square5;
}
}
return 0;
}
//This function shows red color in image button
private void goTofirst3cpu() {
ImageButton imageButton5 = (ImageButton) findViewById(R.id.image_button5);
if (square5 == 0) {
//HERE IS WHAT I NEED TO DO SOMETHING
//when i do something, there will be a gap of 5 seconds
//before changing imagebutton's color from green to red.
//????????? WHAT I WILL DO HERE. ??????
imageButton5.setImageResource(R.color.red_color);
square5 = square5 + 1;
}
}
}
我用了 toast 之类的东西。还有系统时钟。但那些东西对我不起作用。 我需要休息 5 秒才能将图像按钮的颜色更改为红色。 我是编程新手。所以用简单的语言解释一下。 提前致谢......
最佳答案
解决方案:
try
{
Thread.sleep(//milliseconds);
}
catch(InterruptedException e)
{
//handles exception
}
Thread.sleep() 会暂停你的程序一段时间。 建议您捕获异常并正确处理它,因为它可能会给您的程序带来更多问题...
有关中断异常的信息在此重复问题中:
When does Java's Thread.sleep throw InterruptedException?
如果 Thread.sleep() 出现问题,另一种解决方案..
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
int x = 0;
public void actionPerformed(ActionEvent evt) {
if(x == 5)
{
//change color of button...
}
x++;
}
};
new Timer(delay, taskPerformer).start();
你可以做的是实现 Swing Timer在你的程序中。您将创建一个 Timer 对象来每 1000 毫秒触发一次操作。计时器内有一个每秒递增的变量(基本上每次触发操作时),并在该变量等于 5 时执行某些操作。您还可以将计时器设置为 5000 毫秒而不是 1000 作为参数... 要点是,在一段时间后/做某事。
关于java - 如何让所有进程暂停5秒然后继续执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37998413/