美文网首页Android技术知识android技术专栏Android开发
Android ViewPager无限循环,顺滑无卡顿

Android ViewPager无限循环,顺滑无卡顿

作者: Yet_land | 来源:发表于2017-08-07 18:13 被阅读527次

    目的

    多数的APP都有banner功能,banner的实现大多使用的是viewpager,而viewpager自带是没有从最后一页滑到第一页,从第一页滑到第一页。而为了能够更好的体验,需要实现此功能。

    效果图

    可以注意从No.3切换至No.1和No.1切换至No.3之间的过渡。


    效果图

    思路

    例:我们要显示三张图片,分别为No.1,No.2,No.3。

    1. 修改List
      在传入Adapter时的List需要做一下修改,如图:
      List
      当No.1滑动到白色底的No.3且滑动结束时,将currentItem设置为蓝色底的No.3;当从蓝色底的No.3滑动至白色底的No.1且滑动结束时,将currentItem设置为蓝色底的No.1。
      这里要强调的是滑动结束,为何要在滑动结束时才去切换的原因是:若滑动未结束就切换,会出现不连贯的情况(滑动的动画未结束时,就会强行进行切换)。
    2. 为ViewPager添加监听事件
      ViewPager.OnPageChangeListener接口中共有三个方法:onPageScrollStateChanged、onPageScrolled、onPageSelected。当ViewPager滑动时,会分别触发三个方法。在onPageSelected方法中记录position,在onPageScrollStateChanged做切换(当state = 0时)。state = 0 表示动画结束,这样可以做到顺滑,无卡顿。state的定义如下:
        /**
         * Indicates that the pager is in an idle, settled state. The current page
         * is fully in view and no animation is in progress.
         */
        public static final int SCROLL_STATE_IDLE = 0;
    
        /**
         * Indicates that the pager is currently being dragged by the user.
         */
        public static final int SCROLL_STATE_DRAGGING = 1;
    
        /**
         * Indicates that the pager is in the process of settling to a final position.
         */
        public static final int SCROLL_STATE_SETTLING = 2;
    

    代码实现

    代码使用的是kotlin,java类似。

    • Fragment
        lateinit var vpBanner: ViewPager
        val list = ArrayList<Banner>()
        lateinit var adapter: BannerAdapter
        var mPosition = -1
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
        }
    
        override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                                  savedInstanceState: Bundle?): View? {
            if (currentView == null) {
                currentView = inflater!!.inflate(R.layout.fragment_search, container, false)
                vpBanner = currentView!!.vpBanner
    
                val banner = Banner()
                banner.desc = "No.1"
                banner.imgSourceId = R.mipmap.image_banner_1
                val banner2 = Banner()
                banner2.desc = "No.2"
                banner2.imgSourceId = R.mipmap.image_banner_2
                val banner3 = Banner()
                banner3.desc = "No.3"
                banner3.imgSourceId = R.mipmap.image_banner_3
                list.add(banner3)
                list.add(banner)
                list.add(banner2)
                list.add(banner3)
                list.add(banner)
                adapter = BannerAdapter(activity, list)
                vpBanner.adapter = adapter
                vpBanner.setCurrentItem(1, false)
    
                vpBanner.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
                    override fun onPageScrollStateChanged(state: Int) {
                        if (state == 0){
                            if (mPosition == 0) {
                                vpBanner.setCurrentItem(list.size - 2, false)
                            } else if (mPosition == list.size - 1) {
                                vpBanner.setCurrentItem(1, false)
                            }
                        }
                        LogUtils.e("OnPageChangeListener","state -> $state")
                    }
    
                    override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
                        LogUtils.e("OnPageChangeListener", "onPageScrolled,position -> $position,positionOffset -> $positionOffset,positionOffsetPixels -> $positionOffsetPixels")
                    }
    
                    override fun onPageSelected(position: Int) {
                        LogUtils.e("OnPageChangeListener","onPageSelected , position -> $position")
                        mPosition = position
    
                    }
    
                })
    
            }
            return currentView
        }
    
    • Adapter
      Adapter中需要注意的是instantiateItem和destroyItem,此前使用container?.removeViewAt一直会报越界的错误,后面改成container?.removeView就不会了。
    class BannerAdapter constructor(activity: Activity, list: ArrayList<Banner>) : PagerAdapter() {
    
        val mActivity = activity
        val mLIst = list
        lateinit var currentView: View
        lateinit var ivBanner: ImageView
        lateinit var tvDesc: TextView
    
        override fun instantiateItem(container: ViewGroup?, position: Int): Any {
            currentView = LayoutInflater.from(mActivity).inflate(R.layout.item_banner_image, container, false)
            val banner = mLIst[position]
    
            ivBanner = currentView.ivBanner
            tvDesc = currentView.tvDesc
    
            tvDesc.text = banner.desc
    
            Picasso.with(mActivity)
                    .load(banner.imgSourceId)
                    .placeholder(R.mipmap.image_banner_1)
                    .into(ivBanner)
    
            container?.addView(currentView, 0)
            return currentView
        }
    
        override fun isViewFromObject(view: View?, `object`: Any?): Boolean {
            return view == `object`
        }
    
        override fun getCount(): Int {
    
            return mLIst.size
        }
    
        override fun destroyItem(container: ViewGroup?, position: Int, `object`: Any?) {
            LogUtils.e("destroyItem", "destroyItem -> $position")
            container?.removeView(`object` as View?)
        }
    }
    
    • item_banner_image
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">
    
        <ImageView
            android:id="@+id/ivBanner"
            android:layout_width="wrap_content"
            android:layout_height="170dp"
            app:srcCompat="@mipmap/image_banner_1"/>
    
        <TextView
            android:id="@+id/tvDesc"
            android:layout_width="match_parent"
            android:background="#50707070"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/ivBanner"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:text="TextView"/>
    </RelativeLayout>
    
    • Banner
    class Banner {
        var desc: String = ""
        var imgSourceId: Int = -1
    }
    

    相关文章

      网友评论

        本文标题:Android ViewPager无限循环,顺滑无卡顿

        本文链接:https://www.haomeiwen.com/subject/ghualxtx.html