Android App中用Handler实现ViewPager页面的自动切换

在很多电商网页及app上都有自动切换的商品的推广快,感觉体验挺不错的,正好今天学习使用ViewPager,因此也实现了一个功能类似的demo。

下面是其中的两个截图:

实现一个自动播放功能的ViewPager,要做的主要有以下的几个部分:

实现一个ViewPagerAdapter,用于为ViewPager提供展示内容(例如上面的两张小猫图片)

 public class ViewPagerAdapter extends PagerAdapter {
    private List<View> mData;
    public ViewPagerAdapter(List<View> mData) {
      this.mData = mData;
    }

    @Override
    public int getCount() {
      return mData.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
      return arg0 == arg1;
    }
    
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      View v = mData.get(position);
      container.addView(v);
      return v;
    }
    
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//  super.destroyItem(container, position, object);
      container.removeView(mData.get(position));
    }
    
  }

实现一个OnPageChangeListener,这样在页面切换后可以提示当前页面所在的位置(例如上图中,左下角的3个圆点,红色表示当前页面)

 private class ViewPageChangeListener implements OnPageChangeListener {

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    //监听页面改变事件来改变viewIndicator中的指示图片
    @Override
    public void onPageSelected(int arg0) {
      int len = viewIndicator.getChildCount();
      for(int i = 0; i < len; ++i)
        viewIndicator.getChildAt(i).setBackgroundResource(R.drawable.tip_normal);
      viewIndicator.getChildAt(arg0).setBackgroundResource(R.drawable.tip_select);
    }
    
  }

实现一个Handler,用于在一定的时间间隔后修改UI(将当前显示的图片切换到下一个)

private Handler mHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
      switch(msg.what) {
      case 1:
        int totalcount = pagers.size();//autoChangeViewPager.getChildCount();
        int currentItem = autoChangeViewPager.getCurrentItem();
        
        int toItem = currentItem + 1 == totalcount ? 0 : currentItem + 1;
        
        Log.i(TAG, "totalcount: " + totalcount + "  currentItem: " + currentItem + "  toItem: " + toItem);
        
        autoChangeViewPager.setCurrentItem(toItem, true);
        
        //每两秒钟发送一个message,用于切换viewPager中的图片
        this.sendEmptyMessageDelayed(1, 2000);
      }
    }
  };


上面这3段就是主要的代码,除此之外,还需要在onResume()中发送一个起始message以及在onStop()中停止ViewPager页面的自动切换等内容。
完整的代码如下:

public class MainActivity extends Activity {
  private static final String TAG = MainActivity.class.getSimpleName();
  private ViewPager autoChangeViewPager;
  
  //用来指示当前显示图片所在位置
  private LinearLayout viewIndicator;
  
  //包含要在ViewPager中显示的图片
  private List<View> pagers;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    autoChangeViewPager = (ViewPager) findViewById(R.id.autoVP);
    viewIndicator = (LinearLayout) findViewById(R.id.vpindicator);
    
    initAdapter();
    
    //监听页面改变事件来改变viewIndicator中的指示图片
    autoChangeViewPager.setOnPageChangeListener(new ViewPageChangeListener());
    
  }
  
  private void initAdapter() {
    //即将在viewPager中展示的图片资源
    int[] imgs = {R.drawable.i1, R.drawable.i2, R.drawable.i3};
    
    //init pagers;
    pagers = new ArrayList<View>();
    LinearLayout.LayoutParams img_params = new LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT
        );
    for(int i = 0; i < imgs.length; ++i) {
      ImageView iv = new ImageView(this);
      iv.setBackgroundResource(imgs[i]);
      iv.setLayoutParams(img_params);
      final int index = i;
      iv.setOnClickListener(new OnClickListener() {
        //当viewPager中的图片被点击后,跳转到新的activity
        @Override
        public void onClick(View v) {
          Intent i = new Intent(MainActivity.this, InvokedActivity.class);
          i.putExtra("name", "cat " + index);
          MainActivity.this.startActivity(i);
        }
      });
      pagers.add(iv);
    }
    autoChangeViewPager.setAdapter(new ViewPagerAdapter(pagers));
    
    //init indicator
    LinearLayout.LayoutParams ind_params = new LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT
        );
    for(int i = 0; i < imgs.length; ++i) {
      ImageView iv = new ImageView(this);
      if(i == 0)
        iv.setBackgroundResource(R.drawable.tip_select);
      else
        iv.setBackgroundResource(R.drawable.tip_normal);
      iv.setLayoutParams(ind_params);
      viewIndicator.addView(iv);
    }
  }
  
  @Override
  protected void onResume() {
    super.onResume();
    //activity启动两秒钟后,发送一个message,用来将viewPager中的图片切换到下一个
    mHandler.sendEmptyMessageDelayed(1, 2000);
  }
  
  @Override
  protected void onStop() {
    super.onStop();
    //停止viewPager中图片的自动切换
    mHandler.removeMessages(1);
  }

  public class ViewPagerAdapter extends PagerAdapter {
    private List<View> mData;
    public ViewPagerAdapter(List<View> mData) {
      this.mData = mData;
    }

    @Override
    public int getCount() {
      return mData.size();
    }

    @Override
    public boolean isViewFromObject(View arg0, Object arg1) {
      return arg0 == arg1;
    }
    
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      View v = mData.get(position);
      container.addView(v);
      return v;
    }
    
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
//  super.destroyItem(container, position, object);
      container.removeView(mData.get(position));
    }
    
  }
  
  private class ViewPageChangeListener implements OnPageChangeListener {

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    //监听页面改变事件来改变viewIndicator中的指示图片
    @Override
    public void onPageSelected(int arg0) {
      int len = viewIndicator.getChildCount();
      for(int i = 0; i < len; ++i)
        viewIndicator.getChildAt(i).setBackgroundResource(R.drawable.tip_normal);
      viewIndicator.getChildAt(arg0).setBackgroundResource(R.drawable.tip_select);
    }
    
  }
  
  private Handler mHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
      switch(msg.what) {
      case 1:
        int totalcount = pagers.size();//autoChangeViewPager.getChildCount();
        int currentItem = autoChangeViewPager.getCurrentItem();
        
        int toItem = currentItem + 1 == totalcount ? 0 : currentItem + 1;
        
        Log.i(TAG, "totalcount: " + totalcount + "  currentItem: " + currentItem + "  toItem: " + toItem);
        
        autoChangeViewPager.setCurrentItem(toItem, true);
        
        //每两秒钟发送一个message,用于切换viewPager中的图片
        this.sendEmptyMessageDelayed(1, 2000);
      }
    }
  };
}

布局文件如下:(上面代码中的InvokedActivity非常简单,此处就省略了)

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent" >

  <android.support.v4.view.ViewPager
    android:id="@+id/autoVP"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

  <LinearLayout
    android:id="@+id/vpindicator"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:orientation="horizontal" />

</FrameLayout>

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。