今天写代码的时候发现一段模拟延时逻辑内的代码怎么也不执行。延时用的View#postDelayed()
。而对比了下,用Handler#postDelayed()
又没有问题。折腾了好一会。最后发现是执行 view.postDelayed()
之前,view
被remove
了
如果在执行view.postDelayed()
之前,view
被remove
了。那么View#postDelayed()
就会因为View#mAttachInfo
为null
,而将action
发送到View#getRunQueue()
也就是View#mRunQueue
中。
而mRunQueue
中存放的Runnable
(会被包装成HandlerAction
对象)将在何时被执行?
答案是View#dispatchAttachedToWindow
, 顾名思义,会等待View
被添加到window
时,才会被执行,所以如果你的view
被remove
了,那么你postDelayed()
的action
就会等到下次被AttachedToWindow
的时候才会被执行了。