android的viewpager控件的使用

布局文件中布局viewpager:

 

                                    

在代码中使用viewpager:

advPager = (ViewPager) view.findViewById(R.id.adv_pager); List advPics = new ArrayList(); ImageView img1 = new ImageView(getActivity()); img1.setBackgroundResource(R.drawable.page1); advPics.add(img1); ImageView img2 = new ImageView(getActivity()); img2.setBackgroundResource(R.drawable.page2); advPics.add(img2); ImageView img3 = new ImageView(getActivity()); img3.setBackgroundResource(R.drawable.page3); advPics.add(img3); ImageView img4 = new ImageView(getActivity()); img4.setBackgroundResource(R.drawable.page4); advPics.add(img4); ViewGroup group = (ViewGroup) view.findViewById(R.id.viewGroup); imageViews = new ImageView[advPics.size()]; for (int i = 0; i < advPics.size(); i++) { imageView = new ImageView(getActivity()); imageView.setLayoutParams(new LayoutParams(20, 20)); imageView.setPadding(20, 0, 20, 0); 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 View.OnTouchListener() { 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() { public void run() { while (true) { if (isContinue) { viewHandler.sendEmptyMessage(what.get()); whatOption(); } } } }).start(); return view; } private void whatOption() { what.incrementAndGet(); if (what.get() > imageViews.length - 1) { what.getAndAdd(-4); } try { Thread.sleep(2000); } catch (InterruptedException e) { } } private final Handler viewHandler = new Handler() { @Override public void handleMessage(Message msg) { advPager.setCurrentItem(msg.what); super.handleMessage(msg); } };private final class AdvAdapter extends PagerAdapter { private List views = null; public AdvAdapter(List views) { this.views = views; } @Override public void destroyItem(View arg0, int arg1, Object arg2) { ((ViewPager) arg0).removeView(views.get(arg1)); } @Override public void finishUpdate(View arg0) { } @Override public int getCount() { return views.size(); } @Override public Object instantiateItem(View arg0, int arg1) { ((ViewPager) arg0).addView(views.get(arg1), 0); return views.get(arg1); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public void restoreState(Parcelable arg0, ClassLoader arg1) { } @Override public Parcelable saveState() { return null; } @Override public void startUpdate(View arg0) { } }


你可能感兴趣的:(android的viewpager控件的使用)