大图轮播是Android应用中常用的功能,例如网易新闻.总体上的需求分为两个方面:1.无限轮播.2.自动轮播
下面我们来分析以下原理:
无限轮播:将ViewPager的最大的页面值设为Integer.MAX_VALUE,当前的页面值设为Integer.MAX_VALUE/2,如此一来无论用户往左还是往右滑动图片都不可能滑到尽头,这就实现了无限轮播
自动轮播:利用handler发送一个空消息,在handleMessage中将ViewPager的当前页面值+1,在handleMessage中再发送一个延时空消息,循环往复,实现了自动轮播.
1.布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!--ViewPager--> <android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0ff" android:id="@+id/vp"/> <!--底部圆点容器--> <LinearLayout android:layout_alignParentBottom="true" android:layout_width="match_parent" android:layout_height="40dp" android:id="@+id/dot" android:orientation="horizontal" android:background="#ff0" android:gravity="center"/> </RelativeLayout>
2.MainActivity代码
//初始化布局 private void initView() { vp = ((ViewPager) findViewById(R.id.vp)); vp.setOnPageChangeListener(this); dot_view = ((LinearLayout) findViewById(R.id.dot)); }
准备轮播图片和底部圆点
//初始化数据 private void initData() { //存放用于轮播的图片 imageViews = new ArrayList<>();