查看寻呼机定时器应在滑动后重置

时间:2014-01-17 07:37:37

标签: android android-viewpager handler timertask

我有一个每隔6秒刷一次的视图寻呼机。我希望每次手动滑动后计时器重置为6。 即如果我再次滑动页面,计时器应该从0开始。

final Handler handler = new Handler();

        final Runnable Update = new Runnable() {
            public void run() {
                if (currentPage == NUM_PAGES) {
                    currentPage = 0;
                }
                pager.setCurrentItem(currentPage++, true);
            }
        };

        Timer swipeTimer = new Timer();
        swipeTimer.schedule(new TimerTask() {

            @Override
            public void run() {
                handler.post(Update);
            }
        }, 1, 6000);

1 个答案:

答案 0 :(得分:0)

private Handler handler;
private Runnable runnable;
private ViewPager pager;
private int currentPage = 0;
private int time = 3000;    // 3 seconds

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

    ....

    pager = (ViewPager) view.findViewById(R.id.pager);
    pager.setOnPageChangeListener(this);

    startSwipe();

    ....

}

private void startSwipe() {
    MyLog.d(TAG, "startSwipe");
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            if (currentPage == pager.getAdapter().getCount() - 1) {
                currentPage = 0;
            }
            pager.setCurrentItem(currentPage++, true);
            handler.postDelayed(runnable, time);
        }
    };
    handler.postDelayed(runnable, time);
}

private void stopSwipe() {
    MyLog.d(TAG, "stopSwipe");
    handler.removeCallbacks(runnable);
}

@Override
public void onPageScrollStateChanged(int state) {
    MyLog.d(TAG, "onPageScrollStateChanged state: " + state);
    if (state == ViewPager.SCROLL_STATE_DRAGGING) {
        stopSwipe();
        startSwipe();
    }
}

@Override
public void onPause() {
    super.onPause();
    MyLog.d(TAG, "onPause");
    stopSwipe();
}

@Override
public void onResume() {
    super.onResume();
    MyLog.d(TAG, "onResume");
    startSwipe();
}