E/AndroidRuntime: FATAL EXCEPTION: Thread-2 Process: com.xxx.viewsettextdemo, PID: 4387 android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:8191) at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1420) at android.view.View.requestLayout(View.java:24469) at android.view.View.requestLayout(View.java:24469) at android.view.View.requestLayout(View.java:24469) at android.view.View.requestLayout(View.java:24469) at android.view.View.requestLayout(View.java:24469) at android.view.View.requestLayout(View.java:24469) at androidx.constraintlayout.widget.ConstraintLayout.requestLayout(ConstraintLayout.java:3146) at android.view.View.requestLayout(View.java:24469) at android.widget.TextView.checkForRelayout(TextView.java:9681) at android.widget.TextView.setText(TextView.java:6269) at android.widget.TextView.setText(TextView.java:6097) at android.widget.TextView.setText(TextView.java:6049) at com.xxx.viewsettextdemo.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:22) at com.xxx.viewsettextdemo.-$$Lambda$MainActivity$_uRJsNnQ0-zyKYjBJhwoyKb6E_I.run(Unknown Source:2) at java.lang.Thread.run(Thread.java:919)
有什么方法,保证程序不崩溃且能够更新UI?
探讨
问题出现在调用ViewRootImpl.checkThread()方法时,抛出错误:”CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.”
1 2 3 4 5 6
voidcheckThread(){ if (mThread != Thread.currentThread()) { thrownew CalledFromWrongThreadException( "Only the original thread that created a view hierarchy can touch its views."); } }