Can't use setBackgroundResource() when using Thread.sleep on click

99封情书 提交于 2021-02-17 06:37:05

问题


I can successfully change color by using:

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

But if I use

     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?


回答1:


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.

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



回答2:


While the UI thread is sleep()-ing, it cannot render changes to the screen; onDraw() will not execute. In order for a change, such as background color, to be applied, you must completely return control to the framework's message loop (Handler), by returning from the event handler you are in.

Try this instead:

TextView1.setOnClickListener{
    TextView1.setBackgroundResource(R.color.red)
    Handler().postDelayed({
         TextView1.setBackgroundResource(R.color.white)
    }, 1_000)
    //return immediately so that the message loop can render the red background
}



回答3:


Because when you call Thread.sleep(), It will block UI and make UI no change to setBackgroundResource(R.color.red) after sleep() ran, you call setBackgroundResource(R.color.white), so it only updates color white and you no see color red changed



来源:https://stackoverflow.com/questions/59457746/cant-use-setbackgroundresource-when-using-thread-sleep-on-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!