天天看点

自定义ViewPager自动轮播图片(二)

一、布局文件:

1.MainActivity的布局文件:

<LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <com.company.imgscroll.MyImgScroll
                android:id="@+id/tab_find_viewpager"
                android:layout_width="fill_parent"
                android:layout_height="160dp" />

            <LinearLayout
                android:id="@+id/tab_find_vb"
                android:layout_width="match_parent"
                android:layout_height="7dp"
                android:layout_marginTop="-15dp"
                android:gravity="center"
                android:orientation="horizontal" >
            </LinearLayout>
           

2.广告滚动圆点的容器:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <!-- 广告滚动圆点View -->
    <View
        android:id="@+id/ad_item_v"
        android:layout_width="5dip"
        android:layout_height="5dip"
        android:background="@drawable/dot_normal"
        android:layout_marginLeft="2.5dip"
        android:layout_marginRight="2.5dip"
        />

</LinearLayout>
           

二、在Drawable中绘制Xml

3.画出圆点获取焦点的图形:

<?xml version="1.0" encoding="utf-8"?>
<!-- 广告圆点选中 -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >
    <solid android:color="#aa3C3C3C" />
    <corners android:radius="7dip" />
</shape>
           

4.画出圆点未获取焦点的图形:

<?xml version="1.0" encoding="utf-8"?>
<!-- 广告圆点未选中 -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >
    <solid android:color="#33000000" />
    <corners android:radius="5dip" />

</shape>
           

三、自定义MyImgScroll.java

/**
 * 图片滚动类
 * 
 * @author Administrator
 * 
 */
public class MyImgScroll extends ViewPager {
	Activity mActivity; // 上下文
	List<View> mListViews; // 图片组
	int mScrollTime = 0;
	Timer timer;
	int oldIndex = 0;
	int curIndex = 0;

	public MyImgScroll(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	/**
	 * 开始广告滚动
	 * 
	 * @param mainActivity
	 *            显示广告的主界面
	 * @param imgList
	 *            图片列表, 不能为null ,最少一张
	 * @param scrollTime
	 *            滚动间隔 ,0为不滚动
	 * @param ovalLayout
	 *            圆点容器,可为空,LinearLayout类型
	 * @param ovalLayoutId
	 *            ovalLayout为空时 写0, 圆点layout XMl
	 * @param ovalLayoutItemId
	 *            ovalLayout为空时 写0,圆点layout XMl 圆点XMl下View ID
	 * @param focusedId
	 *            ovalLayout为空时 写0, 圆点layout XMl 选中时的动画
	 * @param normalId
	 *            ovalLayout为空时 写0, 圆点layout XMl 正常时背景
	 */
	public void start(Activity mainActivity, List<View> imgList,
			int scrollTime, LinearLayout ovalLayout, int ovalLayoutId,
			int ovalLayoutItemId, int focusedId, int normalId) {
		mActivity = mainActivity;
		mListViews = imgList;
		mScrollTime = scrollTime;
		// 设置圆点
		setOvalLayout(ovalLayout, ovalLayoutId, ovalLayoutItemId, focusedId,
				normalId);
		this.setAdapter(new MyPagerAdapter());// 设置适配器
		if (scrollTime != 0 && imgList.size() > 1) {
			// 设置滑动动画时间  ,如果用默认动画时间可不用 ,反射技术实现
			 new FixedSpeedScroller(mActivity).setDuration(this, 1500);
	
			startTimer();
			// 触摸时停止滚动
			this.setOnTouchListener(new OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) {
					if (event.getAction() == MotionEvent.ACTION_UP) {
						startTimer();
					} else {
						stopTimer();
					}
					return false;
				}
			});
		} 
		if (mListViews.size() > 1) {
			this.setCurrentItem((Integer.MAX_VALUE / 2)
					- (Integer.MAX_VALUE / 2) % mListViews.size());// 设置选中为中间/图片为和第0张一样
		}
	}

	// 设置圆点
	private void setOvalLayout(final LinearLayout ovalLayout, int ovalLayoutId,
			final int ovalLayoutItemId, final int focusedId, final int normalId) {
		if (ovalLayout != null) {
			LayoutInflater inflater=LayoutInflater.from(mActivity);
			for (int i = 0; i < mListViews.size(); i++) {
				ovalLayout.addView(inflater.inflate(ovalLayoutId, null));
				
			}
			//选中第一个
			ovalLayout.getChildAt(0).findViewById(ovalLayoutItemId)
			.setBackgroundResource(focusedId);
			this.setOnPageChangeListener(new OnPageChangeListener() {
				public void onPageSelected(int i) {
					curIndex = i % mListViews.size();
                    //取消圆点选中
					ovalLayout.getChildAt(oldIndex).findViewById(ovalLayoutItemId)
							.setBackgroundResource(normalId);
					 //圆点选中
					ovalLayout.getChildAt(curIndex).findViewById(ovalLayoutItemId)
					.setBackgroundResource(focusedId);
					oldIndex = curIndex;
				}

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

				public void onPageScrollStateChanged(int arg0) {
				}
			});
		}
	}
	/**
	 * 取得当明选中下标
	 * @return
	 */
    public int getCurIndex() {
		return curIndex;
	}
	/**
	 * 停止滚动
	 */
	public void stopTimer() {
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
	}

	/**
	 * 开始滚动
	 */
	public void startTimer() {
		timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				mActivity.runOnUiThread(new Runnable() {
					public void run() {
						MyImgScroll.this.setCurrentItem(MyImgScroll.this
								.getCurrentItem() + 1);
					}
				});
			}
		}, mScrollTime, mScrollTime);
	}

	// 适配器 //循环设置
	private class MyPagerAdapter extends PagerAdapter {
		public void finishUpdate(View arg0) {
		}

		public void notifyDataSetChanged() {
			super.notifyDataSetChanged();
		}

		public int getCount() {
			if (mListViews.size() == 1) {// 一张图片时不用流动
				return mListViews.size();
			}
			return Integer.MAX_VALUE;
		}

		public Object instantiateItem(View v, int i) {
			if (((ViewPager) v).getChildCount() == mListViews.size()) {
				((ViewPager) v)
						.removeView(mListViews.get(i % mListViews.size()));
			}
			((ViewPager) v).addView(mListViews.get(i % mListViews.size()), 0);
			return mListViews.get(i % mListViews.size());
		}

		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == (arg1);
		}

		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		public Parcelable saveState() {
			return null;
		}

		public void startUpdate(View arg0) {
		}

		public void destroyItem(View arg0, int arg1, Object arg2) {
		}
	}
}
           

四、MainActivity中具体实现代码:

public class MainTabFind extends Activity {
        MyImgScroll myPager; // 图片容器
	LinearLayout ovalLayout,carLifeLL; // 圆点容器
	private List<View> listViews; // 图片组
	private View view;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.i(TAG, TAG + "onCreateView");
		view = inflater.inflate(R.layout.main_tab_find, container, false);
		InitView();
		addListener();
		return view;
	}
private void InitView() {
	myPager = (MyImgScroll) view.findViewById(R.id.tab_find_viewpager);
		ovalLayout = (LinearLayout) view.findViewById(R.id.tab_find_vb);
		InitViewPager();// 初始化图片
                InitViewPager();
		// 开始滚动
		myPager.start(getActivity(), listViews, 4000, ovalLayout,
				R.layout.ad_bottom_item, R.id.ad_item_v,
				R.drawable.dot_focused, R.drawable.dot_normal);
	}
private void InitViewPager() {

		listViews = new ArrayList<View>();
		int[] imageResId = new int[] { R.drawable.ad_01,
				R.drawable.ad_02, R.drawable.ad_03,
				R.drawable.ad_04, R.drawable.ad_02 };
		for (int i = 0; i < imageResId.length; i++) {
			ImageView imageView = new ImageView(getActivity());
			imageView.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {// 设置图片点击事件
//					Toast.makeText(getActivity(),//点击viewpager吐司显示了第几页
//							"点击了:" + myPager.getCurIndex(), Toast.LENGTH_SHORT)
//							.show();
				}
			});
			imageView.setImageResource(imageResId[i]);
			imageView.setScaleType(ScaleType.FIT_XY);
			listViews.add(imageView);
		}

	}
@Override
	public void onStop() {
		super.onStop();
		myPager.stopTimer();
	}
}