自定义PageAdapter实现无限轮播

自定义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,然后再添加

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值