button.setText()和Thread.sleep()

问题描述:

Noob问题的方式。在下面的代码中,我更新了Android中按钮的文本。然后我想等待两秒钟,然后再次更新文本。如果我评论第二个b.setText(“发送数据”),则在睡眠之后 - 然后将b.setText(“成功”)写入按钮。如果我不发表评论,我永远不会在按钮上看到文本“成功”,只有“发送数据”。这就像我有第二个b.setText(“发送数据”)时跳过Thread.sleep()。 Google建议在setText(“Success”)之后添加一个计时器,以便setText()代码在睡眠之前有时间被执行。没有帮助。button.setText()和Thread.sleep()

final Button b = (Button) findViewById(R.id.button); 
      b.setText("Send data"); 

      b.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) 
      { 
       b.setClickable(false); 
       b.setText("Success"); 
       System.out.println("Debug before"); 

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

       } 

       System.out.println("Debug after"); 
       b.setText("Send data"); 
       b.setClickable(true); 
    } 
    }); 
+0

您阻止了您的渲染循环。 –

+0

你必须产生一个新线程来做更新。因此,不要在主线程中等待,而是生成一个包含thread.sleep()和更新的新线程。 –

+0

谢谢!我尝试了一些版本,但后来我得到了更新只能由创建按钮的线程完成的错误,这是主线程。 – BjornW

有很多方法可以做到这一点。 你可以运行一个新的线程,然后更新视图。
或者:

 CountDownTimer countDownTimer = new CountDownTimer(2000, 1000) { 
       public void onTick(long millisUntilFinished) { 
       // 
       } 

       public void onFinish() { 
        //update your view 
        System.out.println("Debug after"); 
        b.setText("Send data"); 
       } 
      }; 
      countDownTimer.start(); 
+0

感谢您的帮助! – BjornW

不要堵塞你的主线程。使用Handler.post代替

  b.setClickable(false); 
      b.setText("Success"); 
      System.out.println("Debug before"); 

      new Handler().postDelayed(new Runnable(){ 
       System.out.println("Debug after"); 
       b.setText("Send data"); 
       b.setClickable(true); 
      }, 2000); 
+0

使用这一个,并完美地工作!非常感谢! – BjornW