【问题标题】:Java countdown of three secondsJava倒计时三秒
【发布时间】:2015-03-16 15:58:07
【问题描述】:

我正在开发一个非常简单的纸牌 WAR 游戏 APP,我想在 textview 上显示(3,2,1 -> WAR!)。 这个方法我试过了:

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

    }
}

它没有起作用,只是让我的应用卡住了三秒钟,然后进入活动并放置“WAR!”在 textView..

【问题讨论】:

  • 它只会让我的应用卡住三秒钟。没错,因为你在 UI Thread 上调用 sleep,它也负责绘制
  • 好吧,你正在让主线程休眠三秒钟,所以这就是发生的事情。使用 AsyncTask 或 Runnable/Handlers。
  • 哦.. 那我该怎么做呢?

标签: java android countdown stopwatch


【解决方案1】:

您可以使用此代码:

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();

【讨论】:

    【解决方案2】:

    正确的做法是使用Thread.sleep(long milliseconds),尽管此方法可能会抛出异常,因此您需要像这样将其包围在try and catch中。

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

    【讨论】:

      【解决方案3】:
      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;
      }
      }
      

      已经在 Stackoveflow how to make a countdown timer in java

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多