ViewPager制作循环滚动图片

源地址:http://blog.csdn.net/garry1024/article/details/11909337

原理:

Center

核心代码如下:
private int[] hotIds = new int[] { R.drawable.hot1, R.drawable.hot2,
			R.drawable.hot3, R.drawable.hot4 };
	private List<View> pagerList;
	private LinearLayout pagerPoints;
	
	private void setViewPager() {
		pagerList = new ArrayList<View>();
		for (int i = 0; i < hotIds.length + 2; i++) {
			ImageView iv = new ImageView(SecondActivity.this);
			if (i == 0) {
				iv.setImageResource(hotIds[hotIds.length - 1]);
			} else if (i == hotIds.length + 1) {
				iv.setImageResource(hotIds[0]);
			} else {
				iv.setImageResource(hotIds[i - 1]);
			}
			pagerList.add(iv);
		}

		pagerPoints = (LinearLayout)this.findViewById(R.id.second_pager_point);
		for (int i = 0; i < hotIds.length; i++) {
			ImageView iv = new ImageView(SecondActivity.this);
			iv.setImageResource(R.drawable.selector_pager_point);
			pagerPoints.addView(iv);
		}
		ImageView firstPoint = (ImageView)pagerPoints.getChildAt(0);
		firstPoint.setSelected(true);
		
		mViewPager = (ViewPager) this.findViewById(R.id.second_scroll_picture);

		mViewPager.setAdapter(new PagerAdapter() {

			@Override
			public boolean isViewFromObject(View arg0, Object arg1) {
				// TODO Auto-generated method stub
				return arg0 == arg1;
			}

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return pagerList.size();
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
			
				((ViewPager) container).addView(pagerList.get(position));
				return pagerList.get(position);
			}

			@Override
			public void destroyItem(ViewGroup container, int position,
					Object object) {
			
				((ViewPager) container).removeView(pagerList.get(position));
			}
		});
		mViewPager.setCurrentItem(1); // 设置当前pager为1,即开始时就可以向右活动

		mViewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				// System.out.println("--onPageSelected--" + position);
				for (int i = 0; i < pagerPoints.getChildCount(); i++) {
					pagerPoints.getChildAt(i).setSelected(false);
				}
				//判断是否为最前面的图片,或最后没的图片
				if (position == 0) {
					//pager划到第一页时跳到末尾页
					mViewPager.setCurrentItem(pagerList.size()-2, false);
					//设置所在图片的 点
					pagerPoints.getChildAt( pagerPoints.getChildCount()-1).setSelected(true);
				} else if (position == pagerList.size()-1) {
					//pager划到最后一页时跳到首页
					mViewPager.setCurrentItem(1, false);
					//设置所在图片的 点
					pagerPoints.getChildAt(0).setSelected(true);
				}else{
					//设置所在图片的 点
					pagerPoints.getChildAt(position-1).setSelected(true);
				}

			}

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

			@Override
			public void onPageScrollStateChanged(int position) {
			}
		});

	}


你可能感兴趣的:(viewpager,图片,循环滚动)