1. 范例说明
•android-support-v4.jar,这是谷歌官方给我们提供的一个兼容低版本Android设备的软件包,里面包囊了只有在Android 3.0以上可以使用的api。而ViewPager就是其中之一,利用它我们可以做很多事情,从最简单的导航,到页面切换菜单等等。
•ViewPager的功能就是可以使视图滑动,就像Lanucher左右滑动那样。
•本Demo向大家演示ViewPager的使用,并在用户未滑动View时,每隔5s钟自动切换到下一个View(循环切换),而当用户有Touch到View时取消5s自动切换功能。并有指示器指示当前处于哪一个View。
2. 运行结果
3. 核心代码
private void initViewPager() {
advPager = (ViewPager) findViewById(R.id.adv_pager); ViewGroup group = (ViewGroup) findViewById(R.id.viewGroup); List<View> advPics = new ArrayList<View>(); ImageView img1 = new ImageView(this); img1.setBackgroundResource(R.drawable.advertising_default_1); advPics.add(img1); ImageView img2 = new ImageView(this); img2.setBackgroundResource(R.drawable.advertising_default_2); advPics.add(img2); ImageView img3 = new ImageView(this); img3.setBackgroundResource(R.drawable.advertising_default_3); advPics.add(img3); ImageView img4 = new ImageView(this); img4.setBackgroundResource(R.drawable.advertising_default); advPics.add(img4); imageViews = new ImageView[advPics.size()]; for (int i = 0; i < advPics.size(); i++) { imageView = new ImageView(this); imageView.setLayoutParams(new LayoutParams(20, 20)); imageView.setPadding(5, 5, 5, 5); imageViews[i] = imageView; if (i == 0) { imageViews[i] .setBackgroundResource(R.drawable.banner_dian_focus); } else { imageViews[i] .setBackgroundResource(R.drawable.banner_dian_blur); } group.addView(imageViews[i]); } advPager.setAdapter(new AdvAdapter(advPics)); advPager.setOnPageChangeListener(new GuidePageChangeListener()); advPager.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: isContinue = false; break; case MotionEvent.ACTION_UP: isContinue = true; break; default: isContinue = true; break; } return false; } }); new Thread(new Runnable() { @Override public void run() { while (true) { if (isContinue) { viewHandler.sendEmptyMessage(what.get()); whatOption(); } } } }).start(); }
4. 扩展学习与视频讲解
http://www.eyeandroid.com/thread-11355-1-1.html