网上的答案都一样,都是如果是动画的原因,就用view.post(new Runnable)的方式,但是不知其所以然。
看一下源码就能理解为啥要用这种方式了,如果当前页面已经被销毁或者view已经被remove的情况自然会有空指针问题,采用这种View.post的方式是为了用View类中post方法来做保护,原生代码如下:
/**
* <p>Causes the Runnable to be added to the message queue.
* The runnable will be run on the user interface thread.</p>
*
* @param action The Runnable that will be executed.
*
* @return Returns true if the Runnable was successfully placed in to the
* message queue. Returns false on failure, usually because the
* looper processing the message queue is exiting.
*
* @see #postDelayed
* @see #removeCallbacks
*/
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// Postpone the runnable until we know on which thread it needs to run.
// Assume that the runnable will be successfully placed after attach.
getRunQueue().post(action);
return true;
}