android使用ViewPager实现图片自动切换的方法

1、activity_main.xml布局

创新互联公司专注于柯城企业网站建设,响应式网站开发,成都商城网站开发。柯城网站建设公司,为柯城等地区提供建站服务。全流程定制网站建设,专业设计,全程项目跟踪,创新互联公司专业和态度为您提供的服务


 
 
 

因为我的ViewPager是继承RelativeLayout

2、layout_recommend_item.xml中的布局

<?xml version="1.0" encoding="utf-8"?>

 
 
 

ImageView是显示图片 TextView用来显示每一个pager的标题

3、MyViewPager类,因为图个方便,把能够实现这个功能否合成一个类、这样用起来比较方便

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
 
import java.util.ArrayList;
import java.util.List;
 
public class MyViewPager extends RelativeLayout {
 private static final int START_SCROLL = 1;
 private static final int SCROLL_NEXT = 2;
 private static final int SHOW_TIME = 5000;//显示时间
 private List mDatas = new ArrayList<>();//viewpager每一页对应的标题
 private ViewPager mPager;
 private Context mContext;
 private int mWidth, mHeight; //viewpager的宽高
 private int mTitleHeight;  //标题高度
 private TipView mTipView;  //标题对应的view
 //在主ui中更新viewpager,也就是切换图片
 private static Handler sHandler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
   int w = msg.what;
   ViewPager pager = (ViewPager) msg.obj;
   switch (w) {
    case START_SCROLL:
     pager.setCurrentItem(msg.arg1, true);
     break;
    case SCROLL_NEXT:
     pager.setCurrentItem(msg.arg1, true);
     break;
   }
  }
 };
 
 /**
  * 构造函数
  * @param context content
  * @param w 要显示的viewpager的宽
  * @param h 要显示的viewpager的高
  */
 public MyViewPager(Context context, int w, int h) {
  super(context);
  mContext = context;
  mWidth = w;
  mHeight = h;
  initView(); //取得数据 左边随便取的 只是为了看起来有效果
//  对viewpager滑动进行监听
  mPager.setOnPageChangeListener(new MOnPagerChangeListener());
  init();
  DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
  mTitleHeight = cm_DptoPx(48, dm);
 }
 
 /**
  * 对viewpager控件进行绘制宽高
  */
 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  ViewGroup.LayoutParams vp = getLayoutParams();
  if (vp != null) {
   vp.width = mWidth;
   vp.height = mHeight;
  }
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 }
 
 /**
  * 把dp转化成px
  */
 public static int cm_DptoPx(int dp,DisplayMetrics dis){
  return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, dis);
 }
 
 private void init() {
  getData();
 }
 
 private void initView() {
  mPager = new ViewPager(mContext);
  RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
  addView(mPager, rp);
 }
 
 public void getData() {
  for (int i = 0; i < 4 ; i++){
   mDatas.add(i,"viewpager"+i);
  }
  sHandler.postDelayed(new Runnable() {
   @Override
   public void run() {
    stopAnimation();
    initTipView();
    mPager.setAdapter(new RecommendAdapter());
    mPager.setCurrentItem(10000 * mDatas.size());
   }
  }, 2000);
 }
 
 /**
  * 删除队列中的消息
  */
 public void stopAnimation() {
  sHandler.removeMessages(START_SCROLL);
  sHandler.removeMessages(SCROLL_NEXT);
 }
 public void startAnimation() {
  if (mDatas.size() == 0) {
   return;
  }
  Message msg = sHandler.obtainMessage(START_SCROLL);
  msg.obj = mPager;
  msg.arg1 = (mPager.getCurrentItem() + 1);//取得后一张图片
  sHandler.sendMessageDelayed(msg, SHOW_TIME);//5秒后发送给ui线程
 }
 
 /**
  * 对标题view移动的光标初始化
  */
 private void initTipView() {
 
  if (mTipView == null) {
   RelativeLayout.LayoutParams rp = new RelativeLayout.LayoutParams(10, 10);
   rp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
   rp.bottomMargin = mTitleHeight;
   mTipView = new TipView(mContext, mDatas.size());
   addView(mTipView, rp);
  } else {
   mTipView.setCount(mDatas.size());
  }
 }
 
 
 
 private class MOnPagerChangeListener implements ViewPager.OnPageChangeListener {
  private int curState;
  @Override
  public void onPageScrolled(int i, float v, int i1) {
  }
  @Override
  public void onPageSelected(int i) { //滑动结束
   sHandler.removeMessages(SCROLL_NEXT);
   sHandler.removeMessages(START_SCROLL);
   if(curState == ViewPager.SCROLL_STATE_DRAGGING){
    return;
   }
   Message msg = sHandler.obtainMessage(SCROLL_NEXT);
   msg.arg1 = i + 1;
   msg.obj = mPager;
   sHandler.sendMessageDelayed(msg, SHOW_TIME);
   mTipView.setCurPostion(i % mDatas.size());
  }
 
  @Override
  public void onPageScrollStateChanged(int i) { //正在滑动时
   curState = i;
   if(i == ViewPager.SCROLL_STATE_DRAGGING){ //SCROLL_STATE_DRAGGING正在滑动 SCROLL_STATE_IDLE什么都没有做
    //SCROLL_STATE_SETTLING 滑动完毕
    stopAnimation();
   }else {
    if(!(sHandler.hasMessages(START_SCROLL)&&sHandler.hasMessages(SCROLL_NEXT))){
     startAnimation();
    }
   }
  }
 }
 
 private class RecommendAdapter extends PagerAdapter {
  @Override
  public Object instantiateItem(ViewGroup container, int position) {
   Log.i("MyViewPager","instantiateItem ");
   int curPos = position % mDatas.size();
   View view = View.inflate(mContext, R.layout.layout_recommend_item, null);
   ViewGroup.LayoutParams vp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
   ImageView iv = (ImageView) view.findViewById(R.id.iv_pic);
   TextView tv = (TextView) view.findViewById(R.id.tv_desc);
   tv.setText(mDatas.get(curPos));
   container.addView(view, vp);
   view.setTag(curPos);
   view.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
    }
   });
   return view;
  }
 
  @Override
  public int getCount() {
   return Integer.MAX_VALUE;
  }
 
  @Override
  public boolean isViewFromObject(View view, Object o) {
   return view == o;
  }
 
  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
   container.removeView((View) object);
  }
 }
 
 private class TipView extends View {
 
  private int mPadding;
  private int mCount;
  private int mCurPos;
  private Paint mNorPaint;
  private Paint mSelPaint;
  private int mHeight;
 
  public TipView(Context context, int count) {
   super(context);
   mNorPaint = new Paint();
   mNorPaint.setAntiAlias(true);
   DisplayMetrics dm = context.getResources().getDisplayMetrics();
   int selHeight = cm_DptoPx(2, dm);
   int norHeight = cm_DptoPx(1, dm);
   mHeight = cm_DptoPx(2, dm);
   mNorPaint.setStrokeWidth(norHeight);
   mNorPaint.setColor(Color.argb(80, 255, 255, 255));
   mSelPaint = new Paint();
   mSelPaint.setAntiAlias(true);
   mSelPaint.setStrokeWidth(selHeight);
   mSelPaint.setColor(Color.WHITE);
   mCount = count;
   mPadding = cm_DptoPx(0, dm);
  }
  @Override
  protected void onDraw(Canvas canvas) {
   super.onDraw(canvas);
   int ow = (getWidth()-2*mPadding)/ mCount;
   int y = getHeight() / 2;
   canvas.drawLine(mPadding, y, mCurPos * ow + mPadding, y, mNorPaint);
   canvas.drawLine(mCurPos * ow + mPadding, y, (mCurPos + 1) * ow + mPadding, y, mSelPaint);
   canvas.drawLine((mCurPos + 1) * ow + mPadding, y, getWidth() - mPadding, y, mNorPaint);
  }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   ViewGroup.LayoutParams vp = getLayoutParams();
   vp.width = ViewGroup.LayoutParams.MATCH_PARENT;
   vp.height = mHeight;
   super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  }
 
  public void setCurPostion(int pos) {
   mCurPos = pos;
   invalidate();
  }
 
  public void setCount(int count) {
   mCount = count;
  }
 }
}

4、还有MainActivity中的实现

import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.RelativeLayout;
 
public class MainActivity extends Activity {
 private RelativeLayout mViewPager;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  DisplayMetrics dm = getResources().getDisplayMetrics();
  mViewPager = (RelativeLayout) findViewById(R.id.my_viewpager);
  mViewPager.addView(new MyViewPager(getApplicationContext(),dm.widthPixels ,(dm.widthPixels)/2));
 }
}

网页名称:android使用ViewPager实现图片自动切换的方法
当前网址:http://scyanting.com/article/jjhhse.html