[英]Android: only the original thread that created a view hierarchy can touch its views when calling invalidate()
I'm trying to play a gif using the Movie
object and it requires me to call the invalidate()
method.我正在尝试使用Movie
对象播放 gif,它需要我调用invalidate()
方法。 However whenever I call this method I get the following error:但是,每当我调用此方法时,都会出现以下错误:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
How do I fix this and why is it happening我该如何解决这个问题以及为什么会发生
Runs the specified action on the UI thread.在 UI 线程上运行指定的操作。
I would like to recommend read this site runOnUiThread我想推荐阅读这个网站runOnUiThread
runOnUiThread(new Runnable() {
@Override
public void run() {
// call the invalidate()
}
});
try this尝试这个
final Handler handler=new Handler();
new Thread(new Runnable() {
@Override
public void run() {
//your code
handler.post(new Runnable() {
@Override
public void run() {
invalidate()
}
});
}
}).start();
In Android, only the Main thread (also called the UI thread) can update views.在 Android 中,只有主线程(也称为 UI 线程)可以更新视图。 This is because in Android the UI toolkit s not thread safe.这是因为在 Android 中,UI 工具包不是线程安全的。
When you try to update the UI from a worker thread Android throws this exception.当您尝试从工作线程更新 UI 时,Android 会引发此异常。
Make sure to update the UI from the Main thread.确保从主线程更新 UI。
in case you need it in Kotlin:如果您在 Kotlin 中需要它:
val handler = Handler(Looper.getMainLooper())
handler.post({
invalidate()
})
There's actually a method in the Android SDK you can use to run invalidate() on the UI thread without having to make your own runnable or handler manually, see the official docs here .实际上,Android SDK 中有一种方法可以用来在 UI 线程上运行 invalidate(),而无需手动创建自己的可运行或处理程序,请参阅此处的官方文档。
public void postInvalidate ()
Cause an invalidate to happen on a subsequent cycle through the event loop.导致在通过事件循环的后续循环中发生无效。 Use this to invalidate the View from a non-UI thread.使用它可以使来自非 UI 线程的视图无效。
This method can be invoked from outside of the UI thread only when this View is attached to a window.仅当此 View 附加到窗口时,才能从 UI 线程外部调用此方法。
I know this is an older question and the answers here already work but I had an issue with just using Handler
because by default android studio uses the wrong Handler
object.我知道这是一个较老的问题,这里的答案已经有效,但我在使用Handler
时遇到了问题,因为默认情况下 android studio 使用了错误的Handler
对象。 I had to specify android.os.Handler
ie:我必须指定android.os.Handler
即:
final android.os.Handler handler=new android.os.Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
do_your_ui_stuff_here
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.