2014-07-23 131 views
0

我有圖片數組,我想每5秒更換一張背景圖片,用rundom。 我寫了一些代碼,但我有android.view.ViewRootImpl $ CalledFromWrongThreadException: 只有創建視圖層次結構的原始線程可以觸及其視圖,Exeption。這是什麼問題的解決方案。android每5秒更換背景圖片

public class StradaContact extends Fragment { 

private int[] image_rundow = { 

R.drawable.slideone, R.drawable.slidetwo, R.drawable.slidetree 

}; 

private ImageView mapimg; 
Reminder claass; 

public StradaContact() { 

} 

public static StradaContact newInstance() { 
    return new StradaContact(); 
} 

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
     Bundle savedInstanceState) { 

    View rootView = inflater.inflate(R.layout.strada_contact, container, 
      false); 

    claass = new Reminder(5); 

    return rootView; 
} 

public class Reminder { 

    Timer timer; 

    public Reminder(int seconds) { 
     timer = new Timer(); 
     timer.schedule(new RemindTask(), seconds * 1000); 
    } 

    class RemindTask extends TimerTask { 
     public void run() { 
      while (true) { 
       Random rand = new Random(); 

       int index = rand.nextInt(image_rundow.length); 

       mapimg.setBackgroundResource(image_rundow[index]); 

       timer.cancel(); 
       try { 
        Thread.sleep(5000); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 

      } 

      // Terminate the timer thread 
     } 
    } 
} 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 

} 

}

+0

作爲例外說,只有創建一個視圖的線程可以改變它的屬性。看看AysncTask或View.PostDelayed – CurlyPaul

+0

[Android中的線程UI更新]的可能重複(http://stackoverflow.com/questions/3745405/threading-ui-updates-in-android) – CurlyPaul

回答

0

我提高了你的類: 1.定時器有第三parametr - 區間。 2.用戶界面線程的UI代碼(這是關於mapimg.setBackgroundResource(...)) 如何取消你知道的任務。你可以做到沒有幫助。

public class Reminder { 
     Timer timer; 
     public Reminder(int seconds) { 
      timer = new Timer(); 
      timer.schedule(new RemindTask(), seconds * 1000,5000); 
     } 

     class RemindTask extends TimerTask { 
      public void run() { 
       getActivity().runOnUiThread(new Runnable() { 

         @Override 
         public void run() { 
          Random rand = new Random(); 
          int index = rand.nextInt(image_rundow.length); 
          mapimg.setBackgroundResource(image_rundow[index]); 
         } 
        }); 
       } 
     } 
} 

P.S 我不檢查代碼。也許它有一些錯誤