自定义PageAdapter实现无限轮播
我们要是实现如下图所示无限轮播的ViewPager,使用ViewPager就要写Adapter
自定义PageAdapter需要重写几个方法
-
public int getCount()
-
public Object instantiateItem(@NonNull ViewGroup container, int position)
-
public boolean isViewFromObject(@NonNull View view, @NonNull Object object)
-
public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object)
分别来解释下这几个方法的含义
-
public int getCount()
返回填充数据的大小
注意,如果想实现无限轮播,就需要将这个返回值设置为Integer.MAX_VALUE
如果只是希望从头滑到尾,那就返回填充数据的大小
-
public Object instantiateItem(@NonNull ViewGroup container, int position)
创建给定位置的页面。适配器负责将视图添加到此处给定的容器中,保证执行finishUpdate(ViewGroup)之前完成这个函数的操作
/**
* Create the page for the given position. The adapter is responsible
* for adding the view to the container given here, although it only
* must ensure this is done by the time it returns from
* {@link #finishUpdate(ViewGroup)}.
*
* @param container The containing View in which the page will be shown.
* @param position The page position to be instantiated.
* @return Returns an Object representing the new page. This does not
* need to be a View, but can be some other container of the page.
*/
@NonNull
public Object instantiateItem(@NonNull ViewGroup container, int position) {
return instantiateItem((View) container, position);
}
我们可以得知,instantiateItem是为了填充视图内容,所以,我们在这里将图片集合添加到这个容器中container。
我们这里是实现无限轮播,那就不能使用position来获取图片,如果你设置三张图片,从第三张向右滑需要切换到第一张图片,但是position这个参数会给你返回3(从0开始是第一张照片),就会出现边界越界,那我们如何获取滑到了哪个位置呢,使用取模,position对数据长度取模,当你滑到位置3时,数据长度为3,取模结果为0,正好是第一张图片的位置。
重点来了!!!!!!
重点来了!!!!!!
重点来了!!!!!!
为什么我们要加 if (parent != null) parent.removeView(imageView);
这个判断呢?
如果我们不加这句判断,就会报 java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
异常,因为我们addView的时候,你的view已经有了parent(就是container),不能再添加了,所以,我们需要先判断添加的view是否有parent,如果有,我们就这个view remove,然后再添加