-1

在我的日志中,当前位置为相同的值调用了两次,而我的计时器几乎花费了两倍的时间。NUM_PAGES 实际上占用了我的数组列表的最大大小。

    NUM_PAGES = detailsArrayList.size();

    // Auto start of viewpager
    final Handler handler = new Handler();
    final Runnable Update = new Runnable() {
        public void run() {
            if (currentPage == NUM_PAGES) {
                currentPage = 0;
            }
            Log.d(TAG, "Current Page: " + currentPage);
            mPager.setCurrentItem(currentPage++, false);
        }
    };
    final Timer swipeTimer = new Timer();
    swipeTimer.schedule(new TimerTask() {
        @Override
        public void run() {
            handler.post(Update);
        }
    }, 5000, 5000);

    // Pager listener over indicator
    indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            currentPage = position;
        }

        @Override
        public void onPageScrolled(int pos, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int pos) {
        }
    });
4

1 回答 1

1

我尝试了一个类似的简化代码片段,如下所示:

公共类 MainActivity 扩展 ActionBarActivity { int counter = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            handler.post(Update);
        }
    }, 500, 500);
}

// Auto start of viewpager
final Timer timer = new Timer();
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
    public void run() {
        Log.d("TimerTest", "First Log: " + counter);
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
            Log.d("TimerTest", e.toString());
        }
        //Log.d("TimerTest", "Second Log: " + counter);
        setCounter(counter++);
    }
};

void setCounter(int c) { counter = c; }

代码的结果是:

03-01 19:03:25.936 11865-11865/il.co.falk.timertest D/TimerTest: First Log: 0
03-01 19:03:26.436 11865-11865/il.co.falk.timertest D/TimerTest: First Log: 0
03-01 19:03:26.946 11865-11865/il.co.falk.timertest D/TimerTest: First Log: 0
03-01 19:03:27.456 11865-11865/il.co.falk.timertest D/TimerTest: First Log: 0
03-01 19:03:27.966 11865-11865/il.co.falk.timertest D/TimerTest: First Log: 0
03-01 19:03:28.476 11865-11865/il.co.falk.timertest D/TimerTest: First Log: 0

原因是增量运算符(++)是后缀。它返回旧值,然后递增。

从这里开始,我只能推测。您没有设置功能,但您有与 onPageSelected 类似的功能。当页面被选中时调用它。我猜你有比赛条件。如果它发生在增量之后,你会像我的例子一样留在原地。否则,页面将移动一格。

于 2016-03-01T20:16:44.840 回答