Change layout background dynamically
I want to change layout background dynimically.
Here is the log from the LogCat:
04-10 14:59:55.291: WARN/dalvikvm(263): threadid=15: thread exiting with uncaught exception (group=0x4001b188)
04-10 14:59:55.309: ERROR/AndroidRuntime(263): Uncaught handler: thread Thread-8 exiting due to uncaught exception
04-10 14:59:55.331: ERROR/AndroidRuntime(263): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at android.view.ViewRoot.checkThread(ViewRoot.java:2683)
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at android.view.ViewRoot.req开发者_运维百科uestLayout(ViewRoot.java:557)
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at android.view.View.requestLayout(View.java:7918)
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at android.view.View.requestLayout(View.java:7918)
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at android.view.View.requestLayout(View.java:7918)
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at android.view.View.requestLayout(View.java:7918)
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at android.view.View.setBackgroundDrawable(View.java:7275)
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at android.view.View.setBackgroundResource(View.java:7188)
04-10 14:59:55.331: ERROR/AndroidRuntime(263): at walk.me.Splasher$1.run(Splasher.java:35)
walk.me.Splasher$1.run(Splasher.java:35) is this line:
layout.setBackgroundResource(temp); What should I do?
Use a Handler or run it on the UI thread. A Handler can do this task better.
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
});
You can't modify the user interface from a background thread. See the article PainlessThreading. From the structure of your code, I strongly suggest you use an AsyncTask as described in that article. It allows you to run a background thread that repeatedly triggers actions on the UI thread. Once you learn how to use the AsyncTask class, this kind of thing is easier than feeding individual Runnable objects to a Handler.
精彩评论