如何以编程方式在ViewPager中显示下一个视图?

时间:2011-10-18 03:03:30

标签: android android-viewpager

我创建了一个ViewPager,一切正常,但是我希望在ViewPager之外有一个上一个下一个按钮,可用于在ViewPager中导航。如何在不手动滑动的情况下转到ViewPager上的下一个项目?

4 个答案:

答案 0 :(得分:143)

正如blessenm回答viewpager.setCurrentItem(int index)是要走的路。

答案 1 :(得分:96)

完整的实施只是为了完整性:

public void MoveNext(View view) {
    //it doesn't matter if you're already in the last item
    pager.setCurrentItem(pager.getCurrentItem() + 1);
}

public void MovePrevious(View view) {
    //it doesn't matter if you're already in the first item
    pager.setCurrentItem(pager.getCurrentItem() - 1);
}

答案 2 :(得分:7)

最简单的方法是:

nextButton.setOnClickListener { pager.arrowScroll(View.FOCUS_RIGHT) }
prevButton.setOnClickListener { pager.arrowScroll(View.FOCUS_LEFT) }

答案 3 :(得分:0)

我解决它更好,ty Androiderson。

  private void MoveNextTopSlideShow(View view)
    {
        if (_viewPager_TopImageSlide.CurrentItem == _viewPager_TopImageSlide.ChildCount)
        {
            if (_viewPager_TopImageSlide.ChildCount > 0)
            {
                _viewPager_TopImageSlide.SetCurrentItem(0,true);
            }
        }
        else
        {
            //it doesn't matter if you're already in the last item
            _viewPager_TopImageSlide.SetCurrentItem(_viewPager_TopImageSlide.CurrentItem + 1, true);
        }
    }

    private void MovePreviousTopSlideShow(View view)
    {
        if (_viewPager_TopImageSlide.CurrentItem == 0)
        {
            if (_viewPager_TopImageSlide.ChildCount > 0)
            {
                _viewPager_TopImageSlide.SetCurrentItem(_viewPager_TopImageSlide.ChildCount-1, true);
            }
        }
        else
        {
            //it doesn't matter if you're already in the first item
            _viewPager_TopImageSlide.SetCurrentItem(_viewPager_TopImageSlide.CurrentItem - 1, true);
        }
    }