【问题标题】:button.setText() and Thread.sleep()button.setText() 和 Thread.sleep()
【发布时间】:2017-06-09 19:49:40
【问题描述】:

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

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

【问题讨论】:

  • 你阻塞了你的渲染循环。
  • 您必须生成一个新线程来进行更新。因此,不要在主线程中等待,而是生成一个包含您的 thread.sleep() 和更新的新线程。
  • 谢谢!我尝试了一些版本,但后来我得到了更新只能由创建按钮的线程完成的错误,那就是主线程。

标签: android multithreading settext thread-sleep


【解决方案1】:

不要阻塞你的主线程。改用 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);

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    相关资源
    最近更新 更多