2011-04-10 192 views
0

我想改變佈局背景。動態更改佈局背景

下面是從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.requestLayout(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? 

回答

3

使用處理器或在UI線程上運行它。 A Handler可以更好地完成這項任務。

runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      // TODO Auto-generated method stub 

     } 
    }); 
+0

但我有一個圖像在屏幕上停留了一段時間的同一線程,所以我現在想讓幾個圖像在while循環中發生變化。是否因爲我使用Thread Handler Handler? – 2011-04-10 15:36:33

+0

使用handler.postRunnable(wallPaperRunnable,延遲),你就完成了。閱讀http://developer.android.com/resources/articles/painless-threading.html和http://developer.android.com/reference/android/os/Handler.html – 2011-04-10 15:40:09

2

您不能從後臺線程修改用戶界面。請參閱文章PainlessThreading。從您的代碼結構中,我強烈建議您使用該文章中所述的AsyncTask。它允許你運行一個後臺線程,在UI線程上反覆觸發動作。一旦學習瞭如何使用AsyncTask類,這種事情比將單個Runnable對象提供給Handler更容易。

+0

http:// pastebin中的Handler文檔.com/desptV0g是這樣的嗎? – 2011-04-10 17:40:07

+0

在LinearLayout佈局上給出錯誤=(LinearLayout)findViewById(R.id.splash); line – 2011-04-10 17:41:05

+0

@NikolaMKD - 'findViewById'是另一種只能在UI線程上使用的方法。根據你的代碼,我建議你使用一個帶有LinearLayout參數的構造函數子類AsyncTask(或Thread),並且在設置AsyncTask或Thread時在UI線程上調用findViewById。 – 2011-04-10 19:55:19