Android巧用ViewPager实现左右循环滑动图片

ViewPager这个小demo实现的是可以左右循环滑动图片,下面带索引,滑到最后一页在往右滑动就要第一页,第一页往左滑动就到最后一页,先上效果图:

1、首先看一些layout下的xml

 
   
    
     
    
  
      
      
    
 
 

 使用ViewPager首先需要引入Android-support-v4.jar这个jar包,自己不要忘记加

package com.example.viewpagerdemo; 
 
import android.app.Activity; 
import android.os.Bundle; 
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.ViewGroup.LayoutParams; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
 
public class TwoActivity extends Activity implements OnPageChangeListener{ 
  /** 
   * ViewPager 
   */ 
  private ViewPager viewPager; 
   
  /** 
   * 装点点的ImageView数组 
   */ 
  private ImageView[] tips; 
   
  /** 
   * 装ImageView数组 
   */ 
  private ImageView[] mImageViews; 
   
  /** 
   * 图片资源id 
   */ 
  private int[] imgIdArray ; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    ViewGroup group = (ViewGroup)findViewById(R.id.viewGroup); 
    viewPager = (ViewPager) findViewById(R.id.viewPager); 
     
    //载入图片资源ID 
    imgIdArray = new int[]{R.drawable.item01, R.drawable.item02, R.drawable.item03, R.drawable.item04, 
        R.drawable.item05,R.drawable.item06, R.drawable.item07, R.drawable.item08}; 
     
     
    //将点点加入到ViewGroup中 
    tips = new ImageView[imgIdArray.length]; 
    for(int i=0; i 
 

源码下载:左右滑动ViewPager 

2、上面的代码中,当只有3张图片或者2张图片的时候,滑动存在BUG问题的修改如下
destroyItem(View container, int position, Object object)方法中不removeView

 @Override 
    public void destroyItem(View container, int position, Object object) { 
//     ((ViewPager)container).removeView(mImageViews[position % mImageViews.length]); 
    } 
instantiateItem(View container, int position)增加异常扑捉
@Override 
  public Object instantiateItem(View container, int position) { 
    try {  
      ((ViewPager)container).addView(mImageViews[position % mImageViews.length], 0); 
    }catch(Exception e){ 
      //handler something 
    } 
    return mImageViews[position % mImageViews.length]; 
  } 

以上就是本文的全部内容,希望对大家学习Android软件编程有所帮助。

你可能感兴趣的:(Android巧用ViewPager实现左右循环滑动图片)