最近有些忙,博客一直都没怎么写,回到家就不想碰电脑了,今天抽个空写一写吧。今天要为大家写的是关于ViewPager的文章,其实这个也不算太难吧,网上有很多的资料,看着并不是太好,觉得不太好用。好了进入正题,首先还是先展示工程结构图吧
广告轮播的效果其实就是用这个ViewPager来实现,当然我们肯定需要自定义自己的控件
下面我会贴出自定义控件的代码:
package com.yuriko.viewpager;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class MyViewPager extends ViewPager {
public MyViewPager(Context context) {
super(context);
}
public MyViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
boolean res=super.onInterceptTouchEvent(event);
float Prex=0;
if(event.getAction()==MotionEvent.ACTION_DOWN){
Prex=event.getX();
}else{
if(Math.abs(event.getX()-Prex)>4){
return true;
}else{
Prex=event.getX();
}
}
return res;
}
}
下面我会贴出图片信息的model,可能有些人会问为什么还需要图片信息的model呢。其实原因是这样的,对于轮播的情况下,可能你的图片是个广告类型的,广告图片肯定需要有链接了,所以和纯图片就完全不一样了,还有些可能会需要宣传图片等等。
代码如下:
package com.yuriko.viewpager;
public class Advert {
private String url;
private String advertUrl;
//图片类型,可以是广告图片,纯图片,或者是宣传图片
private int type;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getAdvertUrl() {
return advertUrl;
}
public void setAdvertUrl(String advertUrl) {
this.advertUrl = advertUrl;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
}
现在我们需要在Activity上进行显示了
代码如下:
package com.yuriko.viewpager;
import java.util.ArrayList;
import java.util.List;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;
public class MainActivity extends Activity {
private ImageLoader loader;
//图片的信息集合
private List<Advert> advertList;
private DisplayImageOptions options;
//图片的集合,会将信息转换为图片,并且信息还是需要保存的,因为考虑到图片是什么类型的,比方说可能是广告链接
private List<ImageView> imageList;
private MyViewPager myviewpager;
//页号
private int scrollItem = 0;
/**
* 请求更新显示的View。
*/
protected static final int MSG_UPDATE_IMAGE = 1;
/**
* 请求暂停轮播。
*/
protected static final int MSG_KEEP_SILENT = 2;
/**
* 请求恢复轮播。
*/
protected static final int MSG_BREAK_SILENT = 3;
/**
* 记录最新的页号,当用户手动滑动时需要记录新页号,否则会使轮播的页面出错。
* 例如当前如果在第一页,本来准备播放的是第二页,而这时候用户滑动到了末页,
* 则应该播放的是第一页,如果继续按照原来的第二页播放,则逻辑上有问题。
*/
protected static final int MSG_PAGE_CHANGED = 4;
//轮播间隔时间
protected static final long MSG_DELAY = 3000;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(handler.hasMessages(MSG_UPDATE_IMAGE)){
handler.removeMessages(MSG_UPDATE_IMAGE);
}
switch(msg.what){
//更新view
case MSG_UPDATE_IMAGE:
//页号+1
scrollItem++;
//显示当前页号
myviewpager.setCurrentItem(scrollItem);
//准备下次轮播
handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
break;
//停止轮播
case MSG_KEEP_SILENT:
//不发送任何东西表示停止轮播
break;
//开始轮播
case MSG_BREAK_SILENT:
handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
break;
//记录页号
case MSG_PAGE_CHANGED:
//记录当前页号
scrollItem=msg.arg1;
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myviewpager=(MyViewPager)findViewById(R.id.myviewpager);
//初始化loader,这个就是架包里配置信息。
ImageLoaderConfiguration imageconfig = new ImageLoaderConfiguration.Builder(
getApplication().getApplicationContext())
.threadPoolSize(3)
.threadPriority(Thread.NORM_PRIORITY - 2)
.memoryCacheSize(1500000)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.build();
ImageLoader.getInstance().init(imageconfig);
loader=ImageLoader.getInstance();
initdata();
//开始轮播
handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
}
//初始化数据
public void initdata(){
advertList = new ArrayList<Advert>();
Advert advert = new Advert();
advert.setType(1);
advert.setUrl("http://img1.gtimg.com/ent/pics/hv1/189/195/1748/113713614.jpg");
advertList.add(advert);
Advert advert1 = new Advert();
advert1.setType(1);
advert1.setUrl("http://www.people.com.cn/mediafile/pic/20150418/22/9576752001950563294.jpg");
advertList.add(advert1);
Advert advert2 = new Advert();
advert2.setType(1);
advert2.setUrl("http://www.people.com.cn/mediafile/pic/20150313/26/15661721348234280378.jpg");
advertList.add(advert2);
imageList = new ArrayList<ImageView>();
//得到信息转换成image
for (Advert item : advertList) {
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
ImageView imageView = new ImageView(this);
imageView.setScaleType(ScaleType.FIT_XY);
imageView.setLayoutParams(params);
loader.displayImage(item.getUrl(), imageView,options);
imageList.add(imageView);
}
myviewpager.setAdapter(new ImageAdapter());
//当滑动图片时需要停止轮播,避免滑动的时候开始轮播
myviewpager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int arg0) {
handler.sendMessage(Message.obtain(handler, MSG_PAGE_CHANGED, arg0, 0));
}
@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
@Override
public void onPageScrollStateChanged(int arg0) {
switch (arg0) {
case ViewPager.SCROLL_STATE_DRAGGING:
handler.sendEmptyMessage(MSG_KEEP_SILENT);
break;
case ViewPager.SCROLL_STATE_IDLE:
handler.sendEmptyMessageDelayed(MSG_UPDATE_IMAGE, MSG_DELAY);
break;
default:
break;
}
}
});
}
//adapter
class ImageAdapter extends PagerAdapter{
@Override
public int getCount() {
// TODO Auto-generated method stub
//类似BaseAdapter中获取数据集合的总数,不过这个数很大,是2147483647;
return Integer.MAX_VALUE;
}
@Override
public void destroyItem(View container, int position, Object object) {
// TODO Auto-generated method stub
// super.destroyItem(container, position, object);
}
//类似BaseAdapter中的getview
@Override
public Object instantiateItem(ViewGroup container, int position) {
// TODO Auto-generated method stub
position %=imageList.size();
if(position<0){
position=imageList.size()+position;
}
ImageView imageView=imageList.get(position);
ViewParent vp=imageView.getParent();
if(vp!=null){
ViewGroup parnt=(ViewGroup) vp;
parnt.removeView(imageView);
}
container.addView(imageView);
return imageView;
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
// TODO Auto-generated method stub
return arg0==arg1;
}
}
//这个需要架包
private void setOptions() {
options = new DisplayImageOptions.Builder()
// 设置图片加载或解码过程中发生错误显示的图片
.resetViewBeforeLoading(true)
.cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
// .displayer(new RoundedBitmapDisplayer(100))
.build();
}
}
接下来是xml文件,代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:gravity="center_vertical|center_horizontal"
tools:context=".MainActivity" >
<com.yuriko.viewpager.MyViewPager
android:id="@+id/myviewpager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</LinearLayout>
其实我们还需要一个架包,不过已经在我的工程里了。工程文件请到http://download.csdn.net/detail/u014128885/8773621下载。