参考:
https://www.cnblogs.com/jzyhywxz/p/6914307.html
https://blog.youkuaiyun.com/IAFMAY/article/details/77981293
android-support-v4.jar是Google提供给我们用来兼容低版本Android系统的jar包,ViewPager正是其中之一。
第一步:添加依赖
implementation 'com.android.support:support-v4:25.3.0'
implementation 'com.github.bumptech.glide:glide:4.8.0'
最后的版本号可以搜索后再定,glide是一个非常强大的开源库,主要用于图片加载,在后面的例子中会用到。
第二步:在layout文件中添加VIewPager并获得其引用
layout文件:
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Activity_normal_viewPager">
<android.support.v4.view.ViewPager
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
第三步:为ViewPager设置适配器(最重要的一步)
ViewPager的适配器需要继承PagerAdapter并复写其中的几个方法:
public Object instantiateItem(ViewGroup container, int position):告诉pager adapter创建指定位置的列表项视图,然后将其添加给ViewGroup视图容器
public int getCount():返回pager的总数
public boolean isViewFromObject( View view, Object o):调用instantiateItem()创建完视图后,ViewPager会在某个时间点看到它。为确定视图所属的对象,ViewPager会调用isViewFromObject()方法
public void destroyItem(ViewGroup container, int position, Object object):销毁相应的pager
第四步:为pager添加进出的动画(可选)
pager的进出动画由setPageTransfo