【发布时间】: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