2

I have a ViewPager and a custom PagerAdapter.
In the pager adapter there is a view that onClick I would like to move to the next page.
I implemented the following:

@Override  
public Object instantiateItem(final ViewGroup container, int position) {     
  view.setOnClickListener(
     (view) -> {  
        int current = ((ViewPager)container).getCurrentItem(); 
        ((ViewPager) container).setCurrentItem(current + 1, true);  
    }   
  );    
}    

This works but I am not sure I should be accessing the view pager from inside the adapter like that.
What is the standard way to do this?

Jim
  • 18,826
  • 34
  • 135
  • 254

2 Answers2

0

Your method is ok. If you want cleaner arcitecture you should pass ViewPager as an interface to your adapter. And your code will be like this:

public interface Pager {
    /**
    * Super method where you do 
    * int current = ((ViewPager)container).getCurrentItem(); 
    * ((ViewPager) container).setCurrentItem(current + 1, true);  
    * but in ViewPager. So you don't need to cast it any more.
    */
    void goToNextItem();
}

private Pager pager;

@Override  
public Object instantiateItem(final ViewGroup container, int position) {     
  view.setOnClickListener(
     (view) -> {  
        pager.goToNextItem();
    }   
  );    
}
Anton Potapov
  • 1,265
  • 8
  • 11
  • Is it a good idea to have a reference to the viewpager from the adapter when there is also the reference from the viewpager to the adapter? I.e. circular dependency – Jim Aug 08 '17 at 08:57
  • It's ok. GC can easily handle it, so there is nothing to worry about – Anton Potapov Aug 08 '17 at 08:58
0

@Anton Potapov's method works well, but an easier way would be to make your viewpager public and access it using its parent like below:

((ParentActivity)context).viewPager.setCurrentItem(position++);
Oush
  • 3,090
  • 23
  • 22