【问题标题】:Java Android CountDownTimer malfunctionJava Android CountDownTimer 故障
【发布时间】:2013-10-22 11:23:09
【问题描述】:

我希望我的应用在更改按钮文本之前稍等片刻。我尝试了不同的方法(wait()、Thread.sleep),但由于我希望等待时间可变,我决定使用 CountDownTimer。请看下面的代码:

  public void onClick(View buttonClicked) {
    if (i == 0) {
        button.setText("Wait");
        waitingTime = (long) (Math.random() * 1000 + 10000);
        new countdown(waitingTime, 1000);
        time1 = System.currentTimeMillis();
        button.setText("Press");
        i++;

由于某种原因,这不起作用,程序根本不等待。谁能帮帮我吗?我没有用任何东西填充 CountDownTimer,因为我认为它应该只等待几秒钟。

【问题讨论】:

    标签: java android countdowntimer


    【解决方案1】:

    线程也是可变的:

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

    【讨论】:

      【解决方案2】:

      试试这个代码

      @Override
      public void onClick(View view) {
      if(i==0) {
              YourActivity.this.runOnUiThread(new Runnable() {
      
      
      
      @Override               
      
      public void run() {
      txtView.setText("please wait...");
      }
      });
      
      while(counter < 1000) {
      try {
          Thread.sleep(100);
      }catch(InterruptedException e) {
          e.printStackTrace();
      }
      counter +=100;
      }
      
      txtView.setText("press");
      
      
      i++;
      
      
      }
      
      }
      

      根据你的需要增加线程时间。如果需要,在传递睡眠值的函数中编写此代码

      编辑

      mHandler = new Handler(); btn.setOnClickListener(new OnClickListener() {

              @Override
              public void onClick(View view) {
                  btn.setText("wait");
                  mHandler.postDelayed(new Runnable() {
      
                      @Override
                      public void run() {
                          btn.setText("press");
                      }
                  }, 1500);
              }
          });
      

      【讨论】:

      • 我使用了 Thread.sleep,它确实在等待,但按钮上的文本没有改变...如何正确显示我的代码? > public void onClick(View buttonClicked) { button.setText("Wait"); if (i == 0) { waitingTime = (long) (Math.random() * 1000 + 3000);尝试 { Thread.sleep(waitingTime); } catch (Exception e) { } time1 = System.currentTimeMillis(); button.setText("按下"); i++;
      • YourActivity.this.runOnUiThread(new Runnable() { @Override public void run() { button.setText("Wait"); } });试试这个,而不仅仅是 button.setText("Wait");
      • this
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-09
      • 2014-04-22
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多