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);
}
}
作爲例外說,只有創建一個視圖的線程可以改變它的屬性。看看AysncTask或View.PostDelayed – CurlyPaul
[Android中的線程UI更新]的可能重複(http://stackoverflow.com/questions/3745405/threading-ui-updates-in-android) – CurlyPaul