ViewPager+Timer实现图片轮播
前言
图片轮播在各类手机App中都很常见,尤其是新闻类App(知乎日报)。在 Android 中,使用 ViewPager + Timer + Handler 可以实现这个功能,本文将介绍具体实现。实际运
行效果如下:
运行效果
xml布局
由于 ViewPager 底部小圆点是覆盖在上面的,所以这里使用帧布局 FrameLayout 比较方便。android:layout_gravity="bottom|center" 使圆点指示器底部居中.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context="com.qishun.viewpagerdemo.MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:background="@color/colorPrimary"
android:layout_height="250dp">
<android.support.v4.view.ViewPager
android:id="@+id/mPager"
android:layout_width="wrap_content"
android:layout_height="250dp"/>
<LinearLayout
android:id="@+id/mIndicator"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_gravity="bottom|center"
android:layout_marginBottom="5dp"
android:gravity="center"
android:orientation="horizontal"/>
</FrameLayout>
</LinearLayout>
xml 预览如下:
预览效果
创建图片实体类
接下来创建图片实体 PagerBean 对象,包含图片 id 和图片来源 url。如果需要,还可以加个链接属性,以便在点击图片之后跳转进入指定页面
/**
* Created by zbj on 2017/1/12.
* 图片地址实体类
*/
public class PagerBean {
//新闻ID
private int index;
//新闻图片的url
private String imageUrl;
public PagerBean(int index, String imageUrl) {
this.imageUrl = imageUrl;
this.index = index;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
}
自定义 PagerAdaper 适配器
新建 MyPagerAdapter 继承自 PagerAdapter
构造方法传递集合对象 List<PagerBean> :
private Activity context;
private List<PagerBean> pagers;
private List<SimpleDraweeView> images = new ArrayList<>();
public MyPagerAdapter(Activity context, List<PagerBean> pagers) {
this.context = context;
if (pagers == null || pagers.size() == 0) {
this.pagers = new ArrayList<>();
} else {
this.pagers = pagers;
}
for (int i = 0; i < pagers.size(); i++) {
SimpleDraweeView simpleDraweeView = new SimpleDraweeView(context);
Uri uri = Uri.parse(pagers.get(i).getImageUrl());
simpleDraweeView.setImageURI(uri);
images.add(simpleDraweeView);
}
}
这里我用到的图片缓存框架是 Facebook 开源的 Fresco,附上使用说明。只需创建一个 application 调用 Fresco.initialize 即可完成初始化。然后使用 SimpleDraweeView 代替你所需要的 ImageView 即可。
接着覆写 PagerAdapter 的四个方法:
@Override
public Object instantiateItem(ViewGroup container, int position) {
container.addView(images.get(position));
return images.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(images.get(position));
}
@Override
public int getCount() {
return pagers.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
/*Log.i(TAG, "isViewFromObject view: " + view + " object: "
+ object + " equal: " + (view == object));*/
return view == object;
}
关于这四个函数的详细说明在这儿.
instantiateItem() 用于创建视图,将我们位于具体 position 的视图添加到集合中;
destroyItem() 则是用于从容器中移除视图;
getCount() 返回集合长度即可;
isViewFromObject() 判断 instantiateItem 返回的 object 是否与当前视图是对应的,返回 view == object 即可.
初始化数据和视图
准备工作都做好了,现在就可以在 MainActivity 中添加数据和初始化了。
首先添加底部小圆点指示器
private ImageView[] dots;// 小圆点数组
dots = new ImageView[pagers.size()];// 设置小圆点
int j = dots.length;
for (int i = 0; i < j; i++) {
ImageView dot = new ImageView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
params.setMargins(8, 0, 8, 0);
dot.setLayoutParams(params);
if (i == 0) {
dot.setBackgroundResource(R.drawable.indicator_select);
} else {
dot.setBackgroundResource(R.drawable.indicator_not_select);
}
dots[i] = dot;
mIndicator.addView(dots[i]);
}
给 ViewPager 设置页面滑动事件. 其中我们只需覆写 onPageSelected() 方法,在滚动完成后更改小圆点样式即可
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// 将当前页的小圆点设为选中状态
for (int j = 0; j < dots.length; j++) {
if (j == position) {
dots[j].setBackgroundResource(R.drawable.indicator_select);
} else {
dots[j].setBackgroundResource(R.drawable.indicator_not_select);
}
}
currentIndex = position;// 设置全局变量,currentIndex为选中圆点的Index
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
附上小圆点样式:选中状态 indicator_select.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!--实心填充-->
<solid android:color="#5fcbff"/>
<!-- 边角的圆弧半径 -->
<corners android:radius="2dp"/>
<size
android:width="4dp"
android:height="4dp"/>
</shape>
未选中状态 indicator_not_select.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#dbdbdb"/>
<corners android:radius="2dp"/>
<size
android:width="4dp"
android:height="4dp"/>
</shape>
实现自动循环播放
创建 Handler,在 UI 线程中更新视图
private Handler mHandler = new Handler() {// 定时轮播图片,需要在主线程里面修改UI
@Override
public void handleMessage(Message msg) {
if (msg.what == UPDATE_PAGER) {
if (msg.arg1 != 0) {
mPager.setCurrentItem(msg.arg1);
} else {
// 当从末页调到首页时,不显示翻页动画效果 false
mPager.setCurrentItem(msg.arg1, false);
}
}
}
};
Timer 周期性的向 handler 发送消息以执行更新操作:
// 设置图片自动轮播,5S后执行,周期5S
timer.schedule(new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = UPDATE_PAGER;
if (currentIndex == pagers.size() - 1) {
currentIndex = -1;
}
message.arg1 = currentIndex + 1;
mHandler.sendMessage(message);
}
}, 5000, 5000);
总结
MainActivity 完整代码如下:
public class MainActivity extends AppCompatActivity {
private ViewPager mPager;
private LinearLayout mIndicator;
private ImageView[] dots;// 小圆点数组
private int currentIndex = 0;// 设置当前第几个图片被选中
private static final int UPDATE_PAGER = 0;// 更新图片标记
private Timer timer = new Timer();// 为了方便取消定时轮播,将 Timer 设为全局
private Handler mHandler = new Handler() {// 定时轮播图片,需要在主线程里面修改UI
@Override
public void handleMessage(Message msg) {
if (msg.what == UPDATE_PAGER) {
if (msg.arg1 != 0) {
mPager.setCurrentItem(msg.arg1);
} else {
// 当从末页调到首页时,不显示翻页动画效果 false
mPager.setCurrentItem(msg.arg1, false);
}
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = (ViewPager) findViewById(R.id.mPager);
mIndicator = (LinearLayout) findViewById(R.id.mIndicator);
initData();// 初始化图片数据
}
private void initData() {
List<PagerBean> pagers = new ArrayList();
pagers.add(new PagerBean(1, "http://n.sinaimg.cn/news/20170220/h2n6-fyarrcf4825004.jpg"));
pagers.add(new PagerBean(2, "http://n.sinaimg.cn/photo/20170228/hP2S-fyavvth8349463.jpg"));
pagers.add(new PagerBean(3, "http://n.sinaimg.cn/public_column/20170209/QaSU-fyafqxp6369897.jpg"));
pagers.add(new PagerBean(4, "http://n.sinaimg.cn/photo/20170215/DCav-fyamkqa6273519.jpg"));
initPager(pagers);
}
// 设置适配器,添加指示小圆点
private void initPager(final List<PagerBean> pagers) {
MyPagerAdapter adapter = new MyPagerAdapter(this, pagers);
mPager.setAdapter(adapter);
dots = new ImageView[pagers.size()];// 设置小圆点
int j = dots.length;
for (int i = 0; i < j; i++) {
ImageView dot = new ImageView(MainActivity.this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
params.setMargins(8, 0, 8, 0);
dot.setLayoutParams(params);
if (i == 0) {
dot.setBackgroundResource(R.drawable.indicator_select);
} else {
dot.setBackgroundResource(R.drawable.indicator_not_select);
}
dots[i] = dot;
mIndicator.addView(dots[i]);
}
// 给 viewPager 设置页面滑动事件
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
// 将当前页的小圆点设为选中状态
for (int j = 0; j < dots.length; j++) {
if (j == position) {
dots[j].setBackgroundResource(R.drawable.indicator_select);
} else {
dots[j].setBackgroundResource(R.drawable.indicator_not_select);
}
}
currentIndex = position;// 设置全局变量,currentIndex为选中圆点的Index
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
// 设置图片自动轮播,5S后执行,周期5S
timer.schedule(new TimerTask() {
@Override
public void run() {
Message message = new Message();
message.what = UPDATE_PAGER;
if (currentIndex == pagers.size() - 1) {
currentIndex = -1;
}
message.arg1 = currentIndex + 1;
mHandler.sendMessage(message);
}
}, 5000, 5000);
}
}