天天看點

自定義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();
	}
}