你的位置:首页 > 操作系统

[操作系统]ViewPager+handler实现轮播

先说下功能吧,随便设置一个网络图片链接的集合,作为图片的资源。我用ImageLoader来加载图片,在图片未加载完成时会ProgressBar加载状态

在Handler发送一个空消息来实现页面的轮播

我如下是代码我写在一个类中方面观察

package com.demo.sb.main;import com.demo.suibian.R;import com.nostra13.universalimageloader.core.DisplayImageOptions;import com.nostra13.universalimageloader.core.ImageLoader;import com.nostra13.universalimageloader.core.assist.FailReason;import com.nostra13.universalimageloader.core.assist.ImageScaleType;import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;import android.app.Activity;import android.graphics.Bitmap;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.support.v4.view.PagerAdapter;import android.support.v4.view.ViewPager;import android.support.v4.view.ViewPager.OnPageChangeListener;import android.util.Log;import android.view.MotionEvent;import android.view.View;import android.view.View.OnTouchListener;import android.view.ViewTreeObserver.OnGlobalLayoutListener;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.ImageView.ScaleType;import android.widget.LinearLayout;import android.widget.ProgressBar;import android.widget.RelativeLayout;public class Activity_Other extends Activity {  private ViewPager viewPager;  private ImageLoader loader;  private DisplayImageOptions options;  // private  // private static final int[] mImageIds = new int[] { R.drawable.guide_1,  // R.drawable.guide_2, R.drawable.guide_3 };  // 网上的图片资源  public static final String[] IMAGES = new String[] {      "http://image.tianjimedia.com/uploadImages/2012/067/ORQR14KR5DDC.jpg",      "http://image.tianjimedia.com/uploadImages/2012/067/X6BEO07U962E.jpg",      "http://image.tianjimedia.com/uploadImages/2012/067/F9X84V2ST716.jpg",      "http://image.tianjimedia.com/uploadImages/2012/067/RY445ENQ16BH.jpg",      "http://image.tianjimedia.com/uploadImages/2012/067/74KAJLN0JL95.jpg",      "http://image.tianjimedia.com/uploadImages/2012/067/N80N0GUA36N0.jpg"  };  // private ArrayList<ImageView> mImageViewList;  private LinearLayout llPointGroup;// 引导圆点的父控件  private int mPointWidth;// 圆点间的距离  private View viewRedPoint;// 小红点  // private Handler mhandler;  private Handler mhandler = new Handler() {    public void handleMessage(Message msg) {      int currentItem = viewPager.getCurrentItem();      if (currentItem < IMAGES.length - 1) {        currentItem++;      } else {        currentItem = 0;      }      viewPager.setCurrentItem(currentItem);// 切换到下个页面      mhandler.sendEmptyMessageDelayed(0, 3000);//继续延迟3秒发送消息让Handler继续执行 形成循环    };  };  @Override  protected void onCreate(Bundle savedInstanceState) {    // TODO Auto-generated method stub    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_other);    loader = ImageLoader.getInstance();    options = new DisplayImageOptions.Builder()        .showImageForEmptyUri(R.drawable.ic_empty)        .showImageOnFail(R.drawable.ic_error)        .resetViewBeforeLoading(true).cacheOnDisc(false)        .cacheInMemory(true).imageScaleType(ImageScaleType.EXACTLY)        .bitmapConfig(Bitmap.Config.RGB_565)        .displayer(new FadeInBitmapDisplayer(300)).build();    viewPager = (ViewPager) findViewById(R.id.viewpager1);    llPointGroup = (LinearLayout) findViewById(R.id.ll_point_group);    viewRedPoint = findViewById(R.id.view_red_point);    initViews();    viewPager.setAdapter(new GuideAdapter());    viewPager.setOnPageChangeListener(new GuidePageListener());    mhandler.sendEmptyMessageDelayed(0, 3000);// 延时3秒后发送消息让handler来实现轮播  }  private void initViews() {    // TODO Auto-generated method stub    // mImageViewList = new ArrayList<ImageView>();    //    // // // 初始化引导页的3个页面    // for (int i = 0; i < mImageIds.length; i++) {    // ImageView image = new ImageView(this);    // image.setBackgroundResource(mImageIds[i]);// 设置引导页背景    // mImageViewList.add(image);    // }    for (int i = 0; i < IMAGES.length; i++) {      View point = new View(this);      point.setBackgroundResource(R.drawable.point_normal);// 设置引导页默认圆点      point.setPadding(5, 5, 5, 5);      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(          10, 10);      if (i > 0) {        params.leftMargin = 10;// 设置圆点间隔      }      point.setLayoutParams(params);// 设置圆点的大小      llPointGroup.addView(point);// 将圆点添加给线性布局    }    // 获取视图树, 对layout结束事件进行监听    llPointGroup.getViewTreeObserver().addOnGlobalLayoutListener(        new OnGlobalLayoutListener() {          // 当layout执行结束后回调此方法          @Override          public void onGlobalLayout() {            System.out.println("layout 结束");            llPointGroup.getViewTreeObserver()                .removeGlobalOnLayoutListener(this);            mPointWidth = llPointGroup.getChildAt(1).getLeft()                - llPointGroup.getChildAt(0).getLeft();            System.out.println("圆点距离:" + mPointWidth);          }        });  }  /**   * 触摸监听 当按下时不进行轮播   *   * @author Administrator   *   */  class NewTouchListener implements OnTouchListener {    @Override    public boolean onTouch(View arg0, MotionEvent arg1) {      switch (arg1.getAction()) {      case MotionEvent.ACTION_DOWN:        System.out.println("按下了");        mhandler.removeCallbacksAndMessages(null);        break;      case MotionEvent.ACTION_CANCEL:        System.out.println("事件取消");        mhandler.sendEmptyMessageDelayed(0, 3000);        break;      case MotionEvent.ACTION_UP:        System.out.println("抬起");        mhandler.sendEmptyMessageDelayed(0, 3000);        break;      default:        break;      }      return true;    }  }  /**   * ViewPager数据适配器   *   * @author Kevin   *   */  class GuideAdapter extends PagerAdapter {    @Override    public int getCount() {      return IMAGES.length;    }    @Override    public boolean isViewFromObject(View arg0, Object arg1) {      return arg0 == arg1;    }    @Override    public Object instantiateItem(ViewGroup container, int position) {      // ImageView imageView = new ImageView(Activity_Other.this);      // imageView.setScaleType(ScaleType.FIT_XY);      // loader.displayImage(IMAGES[position], imageView, options);      // container.addView(imageView);      // imageView.setOnTouchListener(new NewTouchListener());      // return imageView;      View imageLayout = View.inflate(Activity_Other.this,          R.layout.item_pager_image, null);      ImageView imageView = (ImageView) imageLayout          .findViewById(R.id.image);      imageView.setScaleType(ScaleType.FIT_XY);      ProgressBar spinBar = (ProgressBar) imageLayout          .findViewById(R.id.loading);      loader.displayImage(IMAGES[position], imageView, options,          new MySimpleLoading(spinBar));      container.addView(imageLayout);      imageView.setOnTouchListener(new NewTouchListener());      return imageLayout;    }    @Override    public void destroyItem(ViewGroup container, int position, Object object) {      container.removeView((View) object);    }  }  class MySimpleLoading extends SimpleImageLoadingListener {    ProgressBar spinBar;    public MySimpleLoading(ProgressBar spinBar) {      // TODO Auto-generated constructor stub      this.spinBar = spinBar;    }    //开始加载    @Override    public void onLoadingStarted(String imageUri, View view) {      // TODO Auto-generated method stub      spinBar.setVisibility(View.VISIBLE);    }    //加载失败    @Override    public void onLoadingFailed(String imageUri, View view,        FailReason failReason) {      // TODO Auto-generated method stub      String message = null;      switch (failReason.getType()) {      case IO_ERROR:        message = "Input/Output error";        break;      case DECODING_ERROR:        message = "Image can't be decoded";        break;      case NETWORK_DENIED:        message = "Downloads are denied";        break;      case OUT_OF_MEMORY:        message = "Out Of Memory error";        break;      case UNKNOWN:        message = "Unknown error";        break;      }      Log.i("ImagePagerAdapter", message);      spinBar.setVisibility(View.GONE);    }    //加载完成    @Override    public void onLoadingComplete(String imageUri, View view,        Bitmap loadedImage) {      // TODO Auto-generated method stub      spinBar.setVisibility(View.GONE);    }  }  /**   * viewpager的滑动监听   *   * @author Kevin   *   */  class GuidePageListener implements OnPageChangeListener {    // 滑动事件    @Override    public void onPageScrolled(int position, float positionOffset,        int positionOffsetPixels) {      // System.out.println("当前位置:" + position + ";百分比:" + positionOffset      // + ";移动距离:" + positionOffsetPixels);      int len = (int) (mPointWidth * positionOffset) + position          * mPointWidth;      RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewRedPoint          .getLayoutParams();// 获取当前红点的布局参数      params.leftMargin = len;// 设置左边距      viewRedPoint.setLayoutParams(params);// 重新给小红点设置布局参数    }    // 某个页面被选中    @Override    public void onPageSelected(int position) {    }    // 滑动状态发生变化    @Override    public void onPageScrollStateChanged(int state) {    }  }}

<?  android:layout_width="match_parent"  android:layout_height="match_parent"  android:orientation="vertical" >  <RelativeLayout    android:layout_width="match_parent"    android:id="@+id/rl_root"    android:layout_height="200dp" >    <android.support.v4.view.ViewPager      android:id="@+id/viewpager1"      android:layout_width="match_parent"      android:layout_height="match_parent" />    <RelativeLayout      android:layout_width="wrap_content"      android:layout_height="wrap_content"      android:layout_alignParentBottom="true"      android:layout_centerHorizontal="true"      android:layout_marginBottom="20dp" >      <LinearLayout        android:id="@+id/ll_point_group"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:orientation="horizontal" >      </LinearLayout>      <View        android:id="@+id/view_red_point"        android:layout_width="8dp"        android:layout_height="8dp"        android:background="@drawable/point_selecte" />    </RelativeLayout>  </RelativeLayout>  <TextView    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:text="@string/app_name" /></LinearLayout>

<?  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:padding="1dip" >  <ImageView    android:id="@+id/image"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_gravity="center"    android:adjustViewBounds="true"    android:contentDescription="@null"    android:scaleType="fitXY" />  <ProgressBar    android:id="@+id/loading"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_gravity="center"    android:visibility="gone" /></FrameLayout>