SoFunction
Updated on 2025-03-11

Android uses ViewPager to achieve automatic image switching

This article realizes the function of viewpager picture carousel, can smoothly switch pictures when sliding left and right, and there are no boundary restrictions.

1. Activity_main.xml layout

<RelativeLayout xmlns:andro
 xmlns:tools="/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 >
 
 <RelativeLayout
  android:
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>
 
</RelativeLayout>

Because my ViewPager inherits RelativeLayout

2. Layout in layout_recommend_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro
 android:orientation="vertical"
 android:layout_width="match_parent"
 android:layout_height="match_parent">
 <ImageView
  android:
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:src="@mipmap/ic_launcher"
  android:layout_weight="1"/>
 <TextView
  android:
  android:text="123"
  android:layout_width="match_parent"
  android:layout_height="wrap_content" />
 
</LinearLayout>

ImageView is used to display the image TextView is used to display the title of each pager

3. MyViewPager class, because it is convenient to synthesize this function into a class, so it is more convenient to use it.

import ;
import ;
import ;
import ;
import ;
import ;
import .;
import .;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
import ;
import ;
 
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;//Show time private List&lt;String&gt; mDatas = new ArrayList&lt;&gt;();//The title of each page of viewpager private ViewPager mPager;
 private Context mContext;
 private int mWidth, mHeight; //The width and height of viewpager private int mTitleHeight;  //Title height private TipView mTipView;  //The corresponding view of the title //Update the viewpager in the main ui, that is, switch pictures private static Handler sHandler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
   int w = ;
   ViewPager pager = (ViewPager) ;
   switch (w) {
    case START_SCROLL:
     (msg.arg1, true);
     break;
    case SCROLL_NEXT:
     (msg.arg1, true);
     break;
   }
  }
 };
 
 /**
   * Constructor
   * @param context content
   * @param w The width of the viewpager to be displayed
   * @param h The height of the viewpager to be displayed
   */
 public MyViewPager(Context context, int w, int h) {
  super(context);
  mContext = context;
  mWidth = w;
  mHeight = h;
  initView(); //Get data. Just get it on the left just to look effective.// Listen to viewpager slide  (new MOnPagerChangeListener());
  init();
  DisplayMetrics dm = ().getDisplayMetrics();
  mTitleHeight = cm_DptoPx(48, dm);
 }
 
 /**
   * Draw the width and height of the viewpager control
   */
 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
   vp = getLayoutParams();
  if (vp != null) {
    = mWidth;
    = mHeight;
  }
  (widthMeasureSpec, heightMeasureSpec);
 }
 
 /**
   * Convert dp to px
   */
 public static int cm_DptoPx(int dp,DisplayMetrics dis){
  return (int) (TypedValue.COMPLEX_UNIT_DIP, dp, dis);
 }
 
 private void init() {
  getData();
 }
 
 private void initView() {
  mPager = new ViewPager(mContext);
   rp = new (.MATCH_PARENT, .MATCH_PARENT);
  addView(mPager, rp);
 }
 
 public void getData() {
  for (int i = 0; i &lt; 4 ; i++){
   (i,"viewpager"+i);
  }
  (new Runnable() {
   @Override
   public void run() {
    stopAnimation();
    initTipView();
    (new RecommendAdapter());
    (10000 * ());
   }
  }, 2000);
 }
 
 /**
   * Delete messages in the queue
   */
 public void stopAnimation() {
  (START_SCROLL);
  (SCROLL_NEXT);
 }
 public void startAnimation() {
  if (() == 0) {
   return;
  }
  Message msg = (START_SCROLL);
   = mPager;
  msg.arg1 = (() + 1);//Get the next picture  (msg, SHOW_TIME);//Send to the ui thread in 5 seconds }
 
 /**
   * Initialize the cursor to move the title view
   */
 private void initTipView() {
 
  if (mTipView == null) {
    rp = new (10, 10);
   (RelativeLayout.ALIGN_PARENT_BOTTOM);
    = mTitleHeight;
   mTipView = new TipView(mContext, ());
   addView(mTipView, rp);
  } else {
   (());
  }
 }
 
 
 
 private class MOnPagerChangeListener implements  {
  private int curState;
  @Override
  public void onPageScrolled(int i, float v, int i1) {
  }
  @Override
  public void onPageSelected(int i) { //Sliding ends   (SCROLL_NEXT);
   (START_SCROLL);
   if(curState == ViewPager.SCROLL_STATE_DRAGGING){
    return;
   }
   Message msg = (SCROLL_NEXT);
   msg.arg1 = i + 1;
    = mPager;
   (msg, SHOW_TIME);
   (i % ());
  }
 
  @Override
  public void onPageScrollStateChanged(int i) { //While sliding   curState = i;
   if(i == ViewPager.SCROLL_STATE_DRAGGING){ //SCROLL_STATE_DRAGGING is sliding SCROLL_STATE_IDLE does nothing    //SCROLL_STATE_SETTLING Sliding completed    stopAnimation();
   }else {
    if(!((START_SCROLL)&amp;&amp;(SCROLL_NEXT))){
     startAnimation();
    }
   }
  }
 }
 
 private class RecommendAdapter extends PagerAdapter {
  @Override
  public Object instantiateItem(ViewGroup container, int position) {
   ("MyViewPager","instantiateItem ");
   int curPos = position % ();
   View view = (mContext, .layout_recommend_item, null);
    vp = new (.MATCH_PARENT, .MATCH_PARENT);
   ImageView iv = (ImageView) (.iv_pic);
   TextView tv = (TextView) (.tv_desc);
   ((curPos));
   (view, vp);
   (curPos);
   (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) {
   ((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();
   (true);
   DisplayMetrics dm = ().getDisplayMetrics();
   int selHeight = cm_DptoPx(2, dm);
   int norHeight = cm_DptoPx(1, dm);
   mHeight = cm_DptoPx(2, dm);
   (norHeight);
   ((80, 255, 255, 255));
   mSelPaint = new Paint();
   (true);
   (selHeight);
   ();
   mCount = count;
   mPadding = cm_DptoPx(0, dm);
  }
  @Override
  protected void onDraw(Canvas canvas) {
   (canvas);
   int ow = (getWidth()-2*mPadding)/ mCount;
   int y = getHeight() / 2;
   (mPadding, y, mCurPos * ow + mPadding, y, mNorPaint);
   (mCurPos * ow + mPadding, y, (mCurPos + 1) * ow + mPadding, y, mSelPaint);
   ((mCurPos + 1) * ow + mPadding, y, getWidth() - mPadding, y, mNorPaint);
  }
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    vp = getLayoutParams();
    = .MATCH_PARENT;
    = mHeight;
   (widthMeasureSpec, heightMeasureSpec);
  }
 
  public void setCurPostion(int pos) {
   mCurPos = pos;
   invalidate();
  }
 
  public void setCount(int count) {
   mCount = count;
  }
 }
}

4. There are also implementations in MainActivity

import ;
import ;
import ;
import ;
 
public class MainActivity extends Activity {
 private RelativeLayout mViewPager;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView(.activity_main);
  DisplayMetrics dm = getResources().getDisplayMetrics();
  mViewPager = (RelativeLayout) findViewById(.my_viewpager);
  (new MyViewPager(getApplicationContext(), ,()/2));
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.