Как заставить ImageSwitcher переключать изображение каждые 5 секунд?
Я пытаюсь заставить ImageSwitcher менять изображение каждые 5 секунд.
Я пытался с помощью Timer
:
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
currentIndex++;
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
},0,5000);
Но я получаю эту ошибку:
LogCat:
12-14 15:07:29.963: E/AndroidRuntime(25592): FATAL EXCEPTION: Timer-0
12-14 15:07:29.963: E/AndroidRuntime(25592): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
2 ответа
Решение
Timer t = new Timer();
//Set the schedule function and rate
t.scheduleAtFixedRate(new TimerTask() {
public void run() {
//Called each time when 1000 milliseconds (1 second) (the period parameter)
currentIndex++;
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
runOnUiThread(new Runnable() {
public void run() {
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
}
},0,5000);
Only the original thread that created a view hierarchy can touch its views.
Задача таймера выполняется в другом потоке. Пользовательский интерфейс должен быть обновлен в пользовательском потоке.
использование runOnUiThread
,
runOnUiThread(new Runnable() {
public void run() {
imageSwitcher.setImageResource(imageIds[currentIndex]);
}
});
Вы также можете использовать Handler
вместо таймера.
Редактировать:
Проверьте, что setBackgroundResource не устанавливает изображение, если это помогает