1 ViewPager2简介
1.1 ViewPager2应用场合
ViewPager2的应用场景:
- 引导界面、相册多图片预览
- 多Tab页面、 App导航
- 广告播放展示
1.2 ViewPager2应用背景
ViewPager2的应用背景:
- androidx.viewpager2:viewpager2
- Names: V4 V7 Androidx etc.
- Android Support Libraries(需要手动加入库)
2 应用案例
2.1 图片轮播
先看看下使用步骤:
- 添加依赖
- xml布局中引用viewpager
- 声明数组,将图片存入
- 创建适配器,完成资源配置
- 为viewpager设置适配器
添加的依赖如下:
要实现的效果如下:
我们首先看下主页面的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".MainActivity">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/pagers"
android:layout_width="match_parent"
android:layout_height="180dp"
android:orientation="horizontal"
app:layout_constraintTop_toTopOf="parent"></androidx.viewpager2.widget.ViewPager2>
<LinearLayout
android:id="@+id/dots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="160dp">
<ImageView
android:layout_width="10dp"
android:layout_height="10dp"
android:background="@drawable/dot_selected"/>
<ImageView
android:layout_width="10dp"
android:layout_height="10dp"
android:background="@drawable/dot_unselected"/>
<ImageView
android:layout_width="10dp"
android:layout_height="10dp"
android:background="@drawable/dot_unselected"/>
<ImageView
android:layout_width="10dp"
android:layout_height="10dp"
android:background="@drawable/dot_unselected"/>