单击时使用Thread.sleep时无法使用setBackgroundResource() [英] Can't use setBackgroundResource() when using Thread.sleep on click

查看:64
本文介绍了单击时使用Thread.sleep时无法使用setBackgroundResource()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用以下方法成功更改颜色:

I can successfully change color by using:

TextView1.setOnClickListener{
 TextView1.setBackgroundResource(R.color.red);
}

但是如果我使用

     TextView1.setOnClickListener{
         TextView1.setBackgroundResource(R.color.red);
         Thread.sleep(1_000)
         TextView1.setBackgroundResource(R.color.white);
        }

颜色完全不变.为什么会这样?

color doesn't change at all. Why is that?

推荐答案

这是由于调用Thread.sleep()只会导致您的线程挂起,在此特定示例中,它导致了GUI(图形用户界面)线程挂.

This is due to the fact that calling Thread.sleep() just causes your thread to hang, in this particular example, it causes the GUI (graphical user interface) thread to hang.

屏幕上gui元素的实际绘制发生在同一线程上,在他调用完方法之后,您没有时间给他这样做.

The actual drawing of the gui elements on the screen occurs on the same thread, right after he is done with calling your methods, you did not give him the time to do so.

您可以通过调度延迟的呼叫来达到相同的结果.

You can achieve the same result by dispatching a delayed call.

TextView1.setOnClickListener {
    TextView1.setBackgroundResource(R.color.red);

    Handler().postDelayed({
        this@MainActivity.runOnUiThread(java.lang.Runnable {
            TextView1.setBackgroundResource(R.color.white);
        })
    }, 1000)
}

这篇关于单击时使用Thread.sleep时无法使用setBackgroundResource()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆