Android 使用 ViewPager 实现自动无限轮播图
在移动应用开发中,首页轮播图是常见的功能需求。Android 原生提供的 ViewPager 组件非常适合实现图片滑动效果,但默认情况下它不支持自动滚动和真正的无限循环。本文将详细介绍如何通过自定义 ViewPager 逻辑来实现自动无限轮播图,包括布局搭建、适配器编写、指示器联动以及自动滚动机制的实现。
一、环境准备
确保项目已引入 Android Support Library 或 AndroidX 的 ViewPager 依赖。如果使用 Gradle 构建,添加以下依赖:
implementation 'androidx.viewpager:viewpager:1.0.0'
二、布局设计
主布局包含一个 RelativeLayout,内部放置 ViewPager 和用于显示指示点的 LinearLayout。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="220dp">
<android.support.v4.view.ViewPager
android:id="@+id/vp_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- 作为 viewgroup 动态 add 游标 -->
<LinearLayout
android:id="@+id/ll_container"
android:layout_width="match_parent"
android:layout_height="30dp"
android:gravity="center"
android:orientation="horizontal"
android:layout_alignParentBottom= />


