我想在用户更改页面时更改背景色,为此,我需要使用ViewPager的setOnPageChangeListener。但这似乎使ViewPagerIndicator停滞不前,因为该指示器卡在了第一页中。这是代码

viewPager.setOnPageChangeListener(new OnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
        ColorDrawable[] colors = {new ColorDrawable(backgroundColors[previousPosition]), new ColorDrawable(backgroundColors[position])};
        TransitionDrawable trans = new TransitionDrawable(colors);
        viewPager.setBackgroundDrawable(trans);
        trans.startTransition(200);
        previousPosition = position;
    }

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

    @Override
    public void onPageScrollStateChanged(int arg0) {}
});

最佳答案

我最终使用ViewPagerIndicator的setOnPageChangeListener而不是ViewPager的方法

mIndicator = (IconPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(viewPager);


代码变为:

mIndicator.setOnPageChangeListener(new OnPageChangeListener() {
    @Override
    public void onPageSelected(int position) {
        ColorDrawable[] colors = {new ColorDrawable(backgroundColors[previousPosition]), new ColorDrawable(backgroundColors[position])};
        TransitionDrawable trans = new TransitionDrawable(colors);
        viewPager.setBackgroundDrawable(trans);
        trans.startTransition(200);
        previousPosition = position;
    }

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

    @Override
    public void onPageScrollStateChanged(int arg0) {}
});

10-07 19:18