Android刷新UI导致崩溃的探究——Only the original thread

一、原因:

非主线程使用TextView.setText(),“有时会出现”Only the original thread that created a view hierarchy can touch its views

二、结论:

setText()会导致文字长度发生改变,如果你的TextView的长度是wrap_content,那么会导致重新计算分配长度,导致运行checkThread()函数,出现错误。虽然可以用非wrap_content修饰达到规避的效果,但这是不推荐的。

三、不推荐简单说明

  • 不能直接理解为由于非主线程刷新UI导致,而是由于某些刷新过程最终执行了checkThread()函数导致的。
void checkThread() {
    
    
	if (mThread != Thread.currentThread()) {
    
    
	    throw new CalledFromWrongThreadException(
	            "Only the original thread that created a view hierarchy can touch its views.");
	}
}
  • checkThread的使用
    在这里插入图片描述
  • requestLayout的使用(一部分)
    在这里插入图片描述
  • 我们可以看到,TextView里面有许多方法都会使用到requestLayout,都会可能导致此错误,所以用取巧的方法规避非主线程刷新的问题,一定是不符合设计初衷的,还是应当在主线程刷新UI!

猜你喜欢

转载自blog.csdn.net/qq_36881363/article/details/107577498