TimerTask and ImageView.setBackgroundDrawable a no-go?
I am trying to set an ImageView's background every x seconds. The used Drawables are downloaded from a server, placed in a Vector and when they all have been downloaded I am starting a Timer and a TimerTask which simply has to set an ImageView in an Activity's Layout.
The problem is that I am getting a : android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I am guessing here thats because of the TimerTask, even though it simply calls a method from the original Activity which in turn sets the ImageView from the local Vector.
This exception isn't thrown every time though, but the times it does go through the ImageView won't show the Image, unless I force a refresh by clicking the device's开发者_开发知识库 "home" button and resuming the app... I have tried to force an update/refresh of the ImageView itself by calling forceLayout() and requestLayout() but that won't do anything :(
So any idea's how to solve these issues ? Should I implement like a Hnadler within the Timer/TimerTask ? Is that even possible ? Will it refresh my ImageView correctly ?
Timer works in a separate thread and (I think) launches it's TimerTasks in a separate threads also, and you can't change UI in a non UI thread (the main thread). The right way, is to use handlers (read documentation, really easy to use, but more for primitive data exchange between non-ui and ui threads), or (the simpliest and more suitable for you) try:
imageView.post(
new Runnable() {
imageView.setBackground(...);
} );
P.S. Usefull:
http://developer.android.com/reference/android/view/View.html#post(java.lang.Runnable) http://developer.android.com/guide/appendix/faq/commontasks.html#threading
精彩评论