Home » Android » android – How to programmatically show next view in ViewPager?

android – How to programmatically show next view in ViewPager?

Posted by: admin March 11, 2020 Leave a comment

Questions:

I created a ViewPager and everything is working fine, however I want to have a previous next button outside of ViewPager which can be used to navigate inside ViewPager. How can I go to next Item on ViewPager without swiping manually?

How to&Answers:

As blessenm answered viewpager.setCurrentItem(int index) is the way to go.

Answer:

A complete implementation just for completeness:

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);
}

Answer:

Easiest way is:

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

Answer:

i fix it Better, 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);
        }
    }