2014-04-03 80 views
0

我正在使用Timer來定期檢查一個條件,並且如果發現真實條件想要刪除背景。但它給了我一個錯誤。如何從線程中刪除背景

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. 

我的代碼是:

t.schedule(new TimerTask(){ 

      @Override 
      public void run() { 

       if(!active){ 
        fl.setBackgroundResource(android.R.color.transparent);// this line causing error ! 

       } 


      }}, 500,500); 
+0

可能重複[?如何使用運行runOnUithread(http://stackoverflow.com/questions/21212631/how-易用,運行runonuithread) – codeMagic

回答

0

嗨,你至少可以使用兩種方法來做到這一點:

1 runOnUIThread活動的方法

runOnUiThread(new Runnable(){ 
    public void run() { 
      // UI code goes here 
    } 
}); 

2 Handler

Handler handler = new Handler(Looper.getMainLooper()); 
handler.post(new Runnable() { 
    public void run() { 
      // UI code goes here 
    } 
}); 
0

使用處理程序來觸摸主線程的觀點類似:

Handler mHandler = new Handler(); 

t.schedule(new TimerTask(){ 

mHandler.post(new TimerTask(){ 

     @Override 
     public void run() { 

      if(!active){ 
       fl.setBackgroundResource(android.R.color.transparent);// this line causing error ! 

      } 
     } 
     }); 
     }, 500,500);