简体   繁体   English

Java倒数三秒

[英]Java countdown of three seconds

I am working on a very simple card WAR game APP, and i wanted to display on a textview (3,2,1 -> WAR!). 我正在开发一个非常简单的纸牌WAR游戏APP,我想在textview上显示(3,2,1-> WAR!)。 I've tried this method: 我试过这种方法:

public void doCounting(){
    for(int i=3;i>=0;i--)
    {
        if(i!=0){
        waitTv.setText("Wait "+i);
        SystemClock.sleep(1000);
        }else{
            waitTv.setText("WAR!");
        }

    }
}

It didnt worked it just make my app stuck for three seconds then enters the activity and place "WAR!" 它没有用,只是让我的应用程序停留了三秒钟,然后进入活动并放置“战争!”。 in the textView.. 在textView中。

The right way to do it is to use the Thread.sleep(long milliseconds) , although this method could throw an exception so you need to surround it in a try and catch like this. 正确的方法是使用Thread.sleep(long milliseconds) ,尽管此方法可能会引发异常,所以您需要像这样尝试捕获它。

try{
    Thread.sleep(3000);
}catch(Exception e){
    e.printStackTrace();
}

You can use this code: 您可以使用以下代码:

CountDownTimer countDownTimer = new CountDownTimer(3, 1000){

        @Override
        public void onTick(long millisUntilFinished) {
            waitTv.setText("Wait " + millisUntilFinished/1000);
        }

        @Override
        public void onFinish() {
            waitTv.setText("WAR!");
        }
    }.start();
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
static int interval;
static Timer timer;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Input seconds => : ");
    String secs = sc.nextLine();
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = Integer.parseInt(secs);
    System.out.println(secs);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            System.out.println(setInterval());

        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}
}

Already on Stackoveflow how to make a countdown timer in java 已经在Stackoveflow上如何在Java中制作倒数计时器

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

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