Android Realizes the Infinite Loop Effect of ViewPager (I)

  • 2021-09-11 21:17:43
  • OfStack

In this paper, we share the specific code of Android to realize ViewPager infinite loop for your reference. The specific contents are as follows

Mode 1:

Implementation principle:

Suppose there are three pictures, They are 1, 2, 3, then create 5 pictures, The order of these five pictures is: 3, 1, 2, 3, 1, where 1, 2, 3 are the pictures we want to slide, and the leftmost 3 and the rightmost 1 are the pictures we add separately. At the beginning, picture 1 is displayed, and when the picture slides to the left, it is 1, 2, 3 in turn. When we continue to slide to the left from the third picture, we will add more pictures 1. At this time, the current index is set to the real picture 1.


package com.xiaomai.myproject.demo;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.xiaomai.myproject.R;
import com.xiaomai.myproject.adapter.LoopViewPagerAdapter;
import com.xiaomai.myproject.base.BaseActivity;
import com.xiaomai.myproject.utils.Utils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by XiaoMai on 2016/10/7 17:19.
 * 
 */
public class LoopViewPagerDemoActivity extends BaseActivity {

 /**
  *  When to update the picture 
  */
 private static final int UPDATE_TIME = 3 * 1000;

 private ViewPager mViewPager;

 private LoopViewPagerAdapter mLoopViewPager;

 /**
  *  Picture resource collection 
  */
 private int[] mImageIds;

 /**
  *  Picture collection 
  */
 private List<ImageView> mImageList;

 /**
  *  Of the current advertisement index
  */
 private int mCurrentPageIndex;

 /**
  *  Indicate Point
  */
 private LinearLayout mLinearLayoutPoints;

 private Handler mHandler = new Handler();

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
 }

 @Override
 protected void onResume() {
  super.onResume();
  mHandler.postDelayed(myRunnable, UPDATE_TIME);
 }

 @Override
 protected void onPause() {
  super.onPause();
  mHandler.removeCallbacks(myRunnable);
 }

 Runnable myRunnable = new Runnable() {
  @Override
  public void run() {
   mViewPager.setCurrentItem(mCurrentPageIndex + 1);
  }
 };

 @Override
 protected void initVariables() {
  super.initVariables();
 }

 @Override
 protected void initViews() {
  mLinearLayoutPoints = (LinearLayout) findViewById(R.id.activity_ll_container);
  mViewPager = (ViewPager) findViewById(R.id.activity_loop_viewpager);
 }

 @Override
 protected void loadData() {
  super.loadData();
  mHandler.postDelayed(new Runnable() {
   @Override
   public void run() {
    /**
     *  Initialize the resources of the picture id
     */
    mImageIds = new int[]{
      R.mipmap.ic_launcher,
      R.mipmap.ic_launcher,
      R.drawable.my_toast,
      R.drawable.my_toast};
    /**
     *  Add ImageView
     */
    mImageList = new ArrayList<>();
    // Add two extra pictures 
    int pagerCount = mImageIds.length + 2;
    ViewGroup.LayoutParams layoutParams =
      new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT);
    for (int i = 0; i < pagerCount; i++) {
     ImageView imageView = new ImageView(mContext);
     imageView.setLayoutParams(layoutParams);
     mImageList.add(imageView);
    }
    // Diameter of dot 
    int diameter = Utils.dip2px(mContext,10f);
    LinearLayout.LayoutParams params =
      new LinearLayout.LayoutParams(diameter, diameter);
    int margin = Utils.dip2px(mContext,5f);
    params.setMargins(margin,margin,margin,margin);
    mLinearLayoutPoints.removeAllViews();
    for (int i = 0; i < mImageList.size(); i++) {
     View view = new View(mContext);
     view.setLayoutParams(params);
     if (i != 0 && i != mImageList.size() - 1) {
      view.setBackgroundResource(R.drawable.circle_normal);
     }
     mLinearLayoutPoints.addView(view);
    }
    mLinearLayoutPoints.setVisibility(View.VISIBLE);
    mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
     @Override
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

     }

     @Override
     public void onPageSelected(int position) {
      mHandler.removeCallbacks(myRunnable);
      mHandler.postDelayed(myRunnable, UPDATE_TIME);
      mCurrentPageIndex = position;
      if (position == 0) {
       //  When the view is in the 1 Set the page number to the last of the picture 1 Zhang. 
       mCurrentPageIndex = mImageIds.length;
      } else if (position == mImageIds.length + 1) {
       //  When the view is at the end 1 Hours , Set the page number to the number of the picture 1 Zhang. 
       mCurrentPageIndex = 1;
      } else {
      }
      /**
       *  When the view is in the 1 One or the last 1 Ten hours, pageIndex And position The values of are not equal, 
       *  So we have to change viewPager Current of item . 
       */
      if (position != mCurrentPageIndex) {
       /**
        *  No. 1 2 Parameter must be set to false It means immediate transition without giving the user a visual effect. 
        */
       mViewPager.setCurrentItem(mCurrentPageIndex, false);
       return;
      }
      for (int i = 1; i < mLinearLayoutPoints.getChildCount() - 1; i++) {
       if (i != mCurrentPageIndex){
        mLinearLayoutPoints.getChildAt(i).setBackgroundResource(R.drawable.circle_normal);
       }else {
        mLinearLayoutPoints.getChildAt(mCurrentPageIndex).setBackgroundResource(
          R.drawable.circle_select);
       }
      }

     }

     @Override
     public void onPageScrollStateChanged(int state) {

     }
    });
    /**
     *  When ViewPager Cancel automatic scrolling when pressed 
     *  On the contrary, turn on automatic sliding. 
     */
    mViewPager.setOnTouchListener(new View.OnTouchListener() {
     @Override
     public boolean onTouch(View v, MotionEvent event) {
      if(event.getAction() == MotionEvent.ACTION_DOWN){
       mHandler.removeCallbacks(myRunnable);
      }else if (event.getAction() == MotionEvent.ACTION_UP){
       mHandler.postDelayed(myRunnable, UPDATE_TIME);
      }
      return false;
     }
    });
    mLoopViewPager = new LoopViewPagerAdapter(mImageList, mImageIds);
    mViewPager.setAdapter(mLoopViewPager);
    /**
     *  Because the first 0 A item Is the picture added separately, so when initializing, you should put the current item Set to 1 . 
     */
    mViewPager.setCurrentItem(1);
    dissMissProgressDialog();
   }
  }, 3 * 1000);

 }

 @Override
 protected int getContentLayout() {
  return R.layout.act_loopviewpager;
 }
}


package com.xiaomai.myproject.adapter;

import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import java.util.List;

/**
 * Created by XiaoMai on 2016/10/7 17:23.
 */
public class LoopViewPagerAdapter extends PagerAdapter {

 private List<ImageView> mImageList;

 private int[] mImageIds;

 public LoopViewPagerAdapter(List<ImageView> mImageList, int[] mImageIds) {
  this.mImageList = mImageList;
  this.mImageIds = mImageIds;
 }

 @Override
 public int getCount() {
  return mImageList == null ? 0 : mImageList.size();
 }

 @Override
 public boolean isViewFromObject(View view, Object object) {
  return view == object;
 }

 @Override
 public Object instantiateItem(ViewGroup container, int position) {
  if (position == 0) {
   //  If it is the first 0 A item Set its picture content to last 1 Contents of 10 pictures 
   mImageList.get(position).setImageResource(mImageIds[mImageIds.length-1]);
  } else if (position == (mImageList.size() - 1)) {
   //  If it is the last 1 A item Set its picture content to the 1 Contents of 10 pictures 
   mImageList.get(position).setImageResource(mImageIds[0]);
  } else {
   //  This is a normal picture 
   mImageList.get(position).setImageResource(mImageIds[position - 1]);
  }
  container.addView(mImageList.get(position));
  return mImageList.get(position);
 }

 @Override
 public void destroyItem(ViewGroup container, int position, Object object) {
  container.removeView(mImageList.get(position));
 }
}

Layout file


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:orientation="vertical">

 <include
  android:id="@+id/titleBar"
  layout="@layout/my_app_bar" />

 <android.support.v4.view.ViewPager
  android:id="@+id/activity_loop_viewpager"
  android:layout_width="match_parent"
  android:layout_height="200dp"
  android:layout_below="@id/titleBar" />

 <LinearLayout
  android:id="@+id/activity_ll_container"
  android:layout_width="match_parent"
  android:orientation="horizontal"
  android:gravity="center"
  android:background="@color/toast"
  android:layout_alignBottom="@id/activity_loop_viewpager"
  android:visibility="gone"
  android:layout_height="40dp"/>
</RelativeLayout>

Related articles: