我想安排一个动作来自动更改我的 ViewPager 页面。我试过了:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
featureViewPager.setCurrentItem(currentPage++, true);
}
}, 100, 500);
但我总是得到:
E/AndroidRuntime(5381): FATAL EXCEPTION: Timer-0
E/AndroidRuntime(5381): java.lang.IllegalStateException: Must be called from main thread of process
我已经在主线程中了对吧?我该如何解决这个问题?
谢谢你的时间。
编辑:
=====================================
感谢您的所有回答。基于这些回复,我遇到了 2 个解决方案:
解决方案 1:
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
featureViewPager.setCurrentItem(currentPage++, true);
}
});
}
}, 500, 3000);
解决方案2:
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
featureViewPager.setCurrentItem(currentPage++, true);
}
};
swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
@Override
public void run() {
handler.post(Update);
}
}, 500, 3000);
哪个更好或者它们是一样的?
再次感谢。