Implementation of ViewPager cyclic advertising space and viewpager cyclic advertising space
1. How to Implement loop playback
2. How to achieve automatic circulation
How to Implement loop playback
Currently, loop playback is implemented on the Internet by returning a large value in the getCount () method of the adapter and using the remainder (position/datas) in instantiateItem (ViewGroup container, int position. the size () method enables the ViewPager to play continuously.
Here we can modify the data source and set currentItem.
Modify Data source:
Final List <Integer> datas = new ArrayList <> (); // Add test data here. In actual projects, you can obtain data from the network. add (R. mipmap. welcome_page_01); datas. add (R. mipmap. welcome_page_02); datas. add (R. mipmap. welcome_page_03); // process the data source datas. add (0, datas. get (datas. size ()-1); datas. add (datas. get (1 ));
Setting currentItem must be performed in the OnPageChangeListener object:
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if(position==0){ mViewPager.setCurrentItem(datas.size()-2,false); }else if(position==datas.size()-1){ mViewPager.setCurrentItem(1,false); } } @Override public void onPageScrollStateChanged(int state) { } });
The Adapter is the same as the Adapter of the general ViewPager.
How to achieve automatic loop:
There are many methods to implement automatic loops, such as Timer, Handler, and Alarm. Here we use Handle
The Custom Handler class is as follows:
public class BannerHander extends Handler{ @Override public void handleMessage(Message msg) { if(msg.what==1){ mViewPager.setCurrentItem(mViewPager.getCurrentItem()+1); sendEmptyMessageDelayed(1,3000); } } }
Get the data. After setting the Adapter for ViewPager, you can start the Automatic loop:
if(!(mHandler!=null && mHandler.get()!=null)){ mHandler = new WeakReference<BannerHander>(new BannerHander());}mHandler.get().sendEmptyMessageDelayed(1, 300);
Here we use weak references to prevent memory overflow.
Note:
When setting CurrentItem, it must be performed in OnPageChangeListener. The finishUpdate (View view) of the Adapter will display a white screen. If anyone knows, please advise.