Android ViewPager之實現輪播廣告效果

相信大多數Android開發者在項目中使用到過ViewPager,其實ViewPager在項目開發中使用 的頻率是非常高的,比如:首次打開項目的嚮導界面以及在輪播圖中都會使用到ViewPager,那麼本篇博客接下來就是記錄使用ViewPager來實現輪播圖效果。

注:ViewPager存在於 Android Support V4包中。

本博客是對使用ViewPager實現輪播廣告效果的封裝,大家在開發中如需使用輪播如功能,可在代碼中直接引用我定義的view——AutoShowView便可實現輪播廣告的效果,如下: 

<com.znouy.viewpagerdemo.view.AutoShowView
        android:id="@+id/asv"
        android:layout_width="match_parent"
        android:layout_height="200dp" >
    </com.znouy.viewpagerdemo.view.AutoShowView>

以下是分析實現過程。

1、在要使用ViewPager自定義view佈局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
 
    <!-- 輪播圖 -->
 
    <android.support.v4.view.ViewPager
        android:id="@+id/vp_lunbo"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </android.support.v4.view.ViewPager>
    <!-- 文字描述和點的容器點和容器 -->
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="#22000000"
        android:gravity="center"
        android:orientation="vertical"
        android:paddingBottom="5dp"
        android:paddingTop="5dp" >
 
        <TextView
            android:id="@+id/tv_desc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="第一個點的描述"
            android:textColor="#ffffff" />
 
        <LinearLayout
            android:id="@+id/ll_points"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
        </LinearLayout>
    </LinearLayout>
 
</RelativeLayout>

佈局如上,對於點我們在代碼中動態添加,但需在xml中定義一個紅點和一個白點,白點如下:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >
 
    <corners android:radius="5dp" />
 
    <solid android:color="#ffffff" />
 
</shape>

2、創建VewPager的適配器PagerAdapter的子類PicturePagerAdapter

首先要提供ViewPager數據,即圖片數據和點數據,代碼如下:

       private void initImageView() {
		for (int i = R.drawable.welcome_1; i < R.drawable.welcome_1 + 4; i++) {
			// 創建ImageView容器
			ImageView imageView = new ImageView(getContext());

			// 設置圖片
			imageView.setImageResource(i);
			imageView.setScaleType(ScaleType.FIT_XY);// 圖片填充容器
			datas.add(imageView);// 添加到集合中
		}
	}

	private void initPoints() {
		// 因爲每次頁面改變都會調用該方法,所以進入該方法時先清空集合。
		ll_points.removeAllViews();

		for (int i = 0; i < datas.size(); i++) {
			View view = new View(getContext());
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					10, 10);
			if (i == selectIndex) {
				tv_desc.setText("圖片" + i + "的描述");
				view.setBackgroundResource(R.drawable.point_red);
			} else {
				view.setBackgroundResource(R.drawable.point_white);
			}
			params.leftMargin = 10;
			view.setLayoutParams(params);// 設置佈局參數
			ll_points.addView(view);// 添加到點的容器中
		}
	}

接着創建PicturePagerAdapter,將數據提供給適配器

public class PicturePagerAdapter extends PagerAdapter {
	private static final String tag = "PicturePagerAdapter";
	List<ImageView> list;

	public PicturePagerAdapter(List<ImageView> imageViews) {
		this.list = imageViews;

	}

	@Override
	public int getCount() {
		// 確定要顯示的數據量

		return Integer.MAX_VALUE;// 無限輪播
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		// 判斷當前要顯示的view是否等於標記object,true則顯示
		return view == object;
	}

	@Override
	public Object instantiateItem(ViewGroup container, int position) {
		position = position % list.size();
		Log.d(tag, "instantiateItem==" + position);
		// 無限輪播-因爲position的值從0~Integer.MAX_VALUE
		View view = list.get(position);
		// 添加view到VIewPager中
		container.addView(view);
		return view;

	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		// 從容器中移除view
		Log.d(tag, "destroyItem==" + position);
		container.removeView((View) object);
	}

}

注意上面適配器的代碼,爲了實現輪播圖的無限輪播,就需保證getCount()返回的數據足夠大,

       @Override
	public int getCount() {
		// 確定要顯示的數據量
		return Integer.MAX_VALUE;// 無限輪播
	}

還有就是當現實到viewpager的最後一張圖片,就要調用viewpager控件的setCurrentItem(10000 - 10000 % datas.size())方法將viewpager顯示第一張圖,代碼是在給viewpager設置適配器後,如下: 

vp_lunbo.setAdapter(adapter);
// 設置ViewPager當前選中的位置,會調用instantiateItem,最終會選中item0
// 原理:一個數減去其餘數後肯定能被除數整除
vp_lunbo.setCurrentItem(10000 - 10000 % datas.size());

3、實現實現輪播圖自動輪播

要實現輪播圖自動輪播,首先需創建一個Runnable接口的子類,代碼如下:

/** 實現輪播圖自動輪播 */

	class AutoScrollTask implements Runnable {

		@Override
		public void run() {
			int currentItem = vp_lunbo.getCurrentItem();
			currentItem++;
			vp_lunbo.setCurrentItem(currentItem);
			start();
		}

		/**
		 * 開始輪播
		 */
		public void start() {
			handler.postDelayed(this, 2000);
		}

		/**
		 * 停止輪播
		 */
		public void stop() {
			handler.removeCallbacks(this);
		}
	}

然後再給viewpager設置觸摸監聽器,實現觸摸停止輪播,鬆開又可以自動輪播了

// viewpager 註冊觸摸事件監聽器,實現自動輪播
vp_lunbo.setOnTouchListener(new OnTouchListener() {

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:// 按下停止輪播
			autoScrollTask.stop();
			break;
		case MotionEvent.ACTION_MOVE:

			break;
		case MotionEvent.ACTION_UP:// 鬆開,取消 開始輪播
		case MotionEvent.ACTION_CANCEL:
			autoScrollTask.start();
			break;

		default:
			break;
		}
		return false;// 不會影響其他view的事件分發
	}
});

4如何使用自定義的輪播圖視圖View

只需在需要使用該輪播圖視圖Viewactivity中進行佈局即可,如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
 
    <com.znouy.viewpagerdemo.view.AutoShowView
        android:id="@+id/asv"
        android:layout_width="match_parent"
        android:layout_height="200dp" >
    </com.znouy.viewpagerdemo.view.AutoShowView>
 
</RelativeLayout>

這樣在以後開發中,如需使用輪播圖效果,直接在activity多對應的佈局引用即可,是不是極大的減輕你開發的工作量了。

以上只是部分代碼,有興趣的請點擊此處下載

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章