简体   繁体   中英

How to access viewpager from a view from the pageradapter?

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?

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 的方法效果很好,但更简单的方法是将您的 viewpager 设为公开并使用其父级访问它,如下所示:

((ParentActivity)context).viewPager.setCurrentItem(position++);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM