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

编辑: admin 分类: 安卓教程 发布时间: 2022-03-14 来源:互联网

本文实现viewpager图片轮播的功能、左右滑动的时候能够流畅的切换图片、并且没有边界限制 

1、activity_main.xml布局

<RelativeLayout 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"
 >
 
 <RelativeLayout
  android:id="@+id/my_viewpager"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>
 
</RelativeLayout>

因为我的ViewPager是继承RelativeLayout

2、layout_recommend_item.xml中的布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <ImageView
  android:id="@+id/iv_pic"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:src="@mipmap/ic_launcher"
  android:layout_weight="1"/>
 <TextView
  android:id="@+id/tv_desc"
  android:text="123"
  android:layout_width="match_parent"
  android:layout_height="wrap_content" />
 
</LinearLayout>

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<String> 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));
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持海外IDC网。

【文章转自高防服务器 http://www.558idc.com 复制请保留原URL】
更多阅读