天天看點

Android無限循環輪轉廣告頁元件實作

       新項目一個,不過又是首頁廣告欄元件,第三次寫這個元件了。雖然也可以拷貝以前的代碼整理一下完成任務,但還是打算封裝一下,重構一下代碼,也算是自己近段時間學習的一個檢驗吧。不錯不錯~~

       先上效果圖(其中第三幅圖是單擊後的跳轉頁面,也是本人的部落格,做下廣告哈!

Android無限循環輪轉廣告頁元件實作

):

Android無限循環輪轉廣告頁元件實作
Android無限循環輪轉廣告頁元件實作
Android無限循環輪轉廣告頁元件實作

       自定義類AdGallery,繼承自Gallery:

package com.wly.android.widget;

import java.util.Timer;
import java.util.TimerTask;

import com.wly.android.widget.AdGalleryHelper.OnGallerySwitchListener;

import net.tsz.afinal.FinalBitmap;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

/**
 * 無限滾動廣告欄元件 持有自身容器布局引用,可以操作滾動訓示器RadioGroup和标題TextView
 * 
 * @author wly
 * @date 2013-12-13
 */
public class AdGallery extends Gallery implements
		android.widget.AdapterView.OnItemClickListener,
		android.widget.AdapterView.OnItemSelectedListener, OnTouchListener {

	private Context mContext;
	private int mSwitchTime; // 圖檔切換時間

	private boolean runflag = false;
	private Timer mTimer; // 自動滾動的定時器

	private OnGallerySwitchListener mGallerySwitchListener;

	private Advertising[] mAds;

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int position = getSelectedItemPosition();
			if (position >= (getCount() - 1)) {
				setSelection(getCount() / 2, true); // 跳轉到第二張圖檔,在向左滑動一張就到了第一張圖檔
				onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
			} else {
				onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
			}
		}
	};

	public AdGallery(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.mContext = context;

		mTimer = new Timer();

	}

	public AdGallery(Context context) {
		super(context);
		this.mContext = context;

		mTimer = new Timer();

	}

	public AdGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.mContext = context;

		mTimer = new Timer();
	}

	class ViewHolder {
		ImageView imageview;
	}

	/**
	 * 初始化配置參數
	 * 
	 * @param ads
	 *            圖檔資料數組
	 * @param switchTime
	 *            圖檔切換間隔
	 * @param l_margin_p
	 *            圖檔到距離螢幕左邊界距離占螢幕的"比例"
	 * @param t_margin_p
	 *            圖檔到距離螢幕上邊界距離占螢幕的"比例"
	 * @param w_percent
	 *            圖檔占螢幕的寬度"比例"
	 * @param h_percent
	 *            圖檔占螢幕的高度"比例"
	 */
	public void init(Advertising[] ads, int switchTime,
			OnGallerySwitchListener gallerySwitchListener) {
		this.mSwitchTime = switchTime;
		this.mGallerySwitchListener = gallerySwitchListener;

		this.mAds = ads;
		setAdapter(new AdAdapter());

		this.setOnItemClickListener(this);
		this.setOnTouchListener(this);
		this.setOnItemSelectedListener(this);
		this.setSoundEffectsEnabled(false);

		// setSpacing(10); //不能包含spacing,否則會導緻onKeyDown()失效!!!
		setSelection(getCount() / 2); // 預設選中中間位置為起始位置
		setFocusableInTouchMode(true);
	}

	class AdAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return mAds.length * (Integer.MAX_VALUE / mAds.length);
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(mContext).inflate(
						R.layout.adgallery_image, null);
				Gallery.LayoutParams params = new Gallery.LayoutParams(
						Gallery.LayoutParams.FILL_PARENT,
						Gallery.LayoutParams.WRAP_CONTENT);
				convertView.setLayoutParams(params);

				viewHolder = new ViewHolder();
				viewHolder.imageview = (ImageView) convertView
						.findViewById(R.id.gallery_image);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			FinalBitmap.create(mContext).display(viewHolder.imageview,
					mAds[position % mAds.length].getPicURL(),
					viewHolder.imageview.getWidth(),
					viewHolder.imageview.getHeight(), null, null);
			return convertView;
		}
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		int kEvent;
		if (isScrollingLeft(e1, e2)) { // 檢查是否往左滑動
			kEvent = KeyEvent.KEYCODE_DPAD_LEFT;
		} else { // 檢查是否往右滑動
			kEvent = KeyEvent.KEYCODE_DPAD_RIGHT;
		}

		onKeyDown(kEvent, null);
		return true;

	}

	private boolean isScrollingLeft(MotionEvent e1, MotionEvent e2) {
		return e2.getX() > (e1.getX() + 50);
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		return super.onScroll(e1, e2, distanceX, distanceY);
	}

	/**
	 * 開始自動滾動
	 */
	public void startAutoScroll() {
		mTimer.schedule(new TimerTask() {

			public void run() {
				if (runflag) {
					Message msg = new Message();
					if (getSelectedItemPosition() < (getCount() - 1)) {
						msg.what = getSelectedItemPosition() + 1;
					} else {
						msg.what = 0;
					}
					handler.sendMessage(msg);
				}
			}
		}, mSwitchTime, mSwitchTime);

	}

	public void setRunFlag(boolean flag) {
		runflag = flag;
	}

	public boolean isAutoScrolling() {
		if (mTimer == null) {
			return false;
		} else {
			return true;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (MotionEvent.ACTION_UP == event.getAction()
				|| MotionEvent.ACTION_CANCEL == event.getAction()) {
			// 重置自動滾動任務
			setRunFlag(true);
		} else {
			// 停止自動滾動任務
			setRunFlag(false);
		}
		return false;
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View arg1, int position,
			long arg3) {

		mGallerySwitchListener.onGallerySwitch(position % (mAds.length));

	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		Intent i = new Intent();
		i.setClass(mContext, MyWebViewActivity.class);
		i.putExtra("url", mAds[position % mAds.length].getLinkURL());
		mContext.startActivity(i);
	}
}
           

       以上代碼核心就是用一個定時器Timer不斷的發送Message個一個Handler,在Handler的handleMessage()方法中手動的切換Gallery元件,有兩點需要注意:

       1、gallery不能包含spacing屬性,即使将該屬性設定為0dp也不行,否則會導緻onKeyDown()事件失效。另外不要使用setSelection(),因為使用setSelection()隻是實作的切換,但沒有動畫效果。

       2、廣告欄下方标題必須指定最大長度為一個固定值,否則會在自動切換時發生抖動,這是筆者遇到的一個問題。

再對其進行一個簡單的封裝(添加一個标題TextView和RadioGroup),建立類AdGalleryHelper:

package com.wly.android.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.RelativeLayout.LayoutParams;

/**
 * 對自定義元件AdGallery進行了一次封裝
 * 包含對圖檔标題和目前位置訓示器(RadioGroup)的操作
 * @author wly
 *
 */
public class AdGalleryHelper {

	private AdGallery mAdGallery; //無限滾動Gallery
	private TextView mPicTitle; //廣告圖檔标題
	private RadioGroup mRadioGroup; //滾動标記元件
	
	private Context mContext;
	private LayoutInflater mInflater;
	
	RelativeLayout galleryLayout;
	

	public AdGalleryHelper(Context context,final Advertising[] ads,int switchTime) {
		
		this.mContext = context;
		mInflater = LayoutInflater.from(context);
		galleryLayout = (RelativeLayout)mInflater.inflate(R.layout.adgallery_hellper, null);
		mRadioGroup = (RadioGroup)galleryLayout.findViewById(R.id.home_pop_gallery_mark);
		
		//添加RadioButton
		Bitmap b = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.point_1);
		LayoutParams params = new LayoutParams(
				Util.dpToPx(mContext, b.getWidth()), 
				Util.dpToPx(mContext, b.getHeight()));
		for (int i = 0; i < ads.length; i++) {
			RadioButton _rb = new RadioButton(mContext);
			_rb.setId(0x1234 + i);
			_rb.setButtonDrawable(mContext.getResources().getDrawable(
					R.drawable.gallery_selector));
			mRadioGroup.addView(_rb, params);
		}
		
		
		mPicTitle = (TextView)galleryLayout.findViewById(R.id.news_gallery_text);
		mAdGallery = (AdGallery)galleryLayout.findViewById(R.id.gallerypop);
		mAdGallery.init(ads, switchTime,new OnGallerySwitchListener() {
			
			@Override
			public void onGallerySwitch(int position) {
				if (mRadioGroup != null) {
					mRadioGroup.check(mRadioGroup.getChildAt(
							position).getId());
				}
				if(mPicTitle != null) {
					mPicTitle.setText(ads[position].getTitle());
				}
			}
		});
		
	}
	
	/**
	 * 向外開放布局對象,使得可以将布局對象添加到外部的布局中去
	 * @return
	 */
	public RelativeLayout getLayout() {
		return galleryLayout;
	}
	
	/**
	 * 開始自動循環切換
	 */
	public void startAutoSwitch() {
		mAdGallery.setRunFlag(true);
		mAdGallery.startAutoScroll();
	}

	public void stopAutoSwitch() {
		mAdGallery.setRunFlag(true);
	}
	
	/**
	 * 圖檔切換回調接口
	 * @author wly
	 *
	 */
	interface OnGallerySwitchListener {
		public void onGallerySwitch(int position);
	}
}
           

       實體類Advertising:

package com.wly.android.widget;

/**
 * 廣告實體類
 * @author wly
 *
 */
public class Advertising {

	private String picURL; //圖檔位址
	private String linkURL; //單擊跳轉位址
	private String title; //标題
	
	public Advertising(String picURL, String linkURL, String title) {
		super();
		this.picURL = picURL;
		this.linkURL = linkURL;
		this.title = title;
	}
	
	public String getPicURL() {
		return picURL;
	}
	public void setPicURL(String picURL) {
		this.picURL = picURL;
	}
	public String getLinkURL() {
		return linkURL;
	}
	public void setLinkURL(String linkURL) {
		this.linkURL = linkURL;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
}
           

       Activity界面類MainActivity:

package com.wly.android.widget;


import java.io.File;

import net.tsz.afinal.FinalBitmap;


import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class MainActivity extends Activity {

	RelativeLayout galleryContainer; //滾動廣告元件的容器
	LayoutInflater inflater;
	AdGalleryHelper mGalleryHelper;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		//============初始化緩存路徑,以及AfinalBitmap的初始化,可以忽略
		String cacheDir;
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			File f = this.getApplicationContext().getExternalCacheDir();
			if (null == f) {

				cacheDir = Environment.getExternalStorageDirectory().getPath()
						+ File.separator + this.getApplicationContext().getPackageName()
						+ File.separator + "cache";
			} else {
				cacheDir = f.getPath();
			}
		} else {
			File f = this.getApplicationContext().getCacheDir();
			cacheDir = f.getPath();
		}
		FinalBitmap.create(this, cacheDir + File.separator
				+ "images" + File.separator,
				0.3f, 1024 * 1024 * 10,
				 10);
		//==================
		
		//構造測試資料
		Advertising ad1 = new Advertising("https://img-my.csdn.net/uploads/201312/14/1386989803_3335.PNG"
				, "http://blog.csdn.net/u011638883/article/details/17302293"
				, "雙向搜尋");
		Advertising ad2 = new Advertising("https://img-my.csdn.net/uploads/201312/14/1386989613_6900.jpg"
				, "http://blog.csdn.net/u011638883/article/details/17245371"
				, "創意設計");
		Advertising ad3 = new Advertising("https://img-my.csdn.net/uploads/201312/14/1386989802_7236.PNG"
				, "http://blog.csdn.net/u011638883/article/details/17248135"
				, "Artificial Intelligence");
		Advertising[] ads = {ad1,ad2,ad3};
		
		//将AdGalleryHelper添加到布局檔案中
		galleryContainer = (RelativeLayout) this
				.findViewById(R.id.home_gallery);
		mGalleryHelper = new AdGalleryHelper(this, ads, 5000);
		galleryContainer.addView(mGalleryHelper.getLayout());
		
		//開始自動切換	
		mGalleryHelper.startAutoSwitch(); 
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mGalleryHelper.stopAutoSwitch();
	}
}
           

       注意,代碼中異步加載圖檔使用的Afinal架構的FinalBitmap。讀者可以根據自己項目加以替換。

       代碼工程:http://download.csdn.net/detail/u011638883/6713923

       用到的Afinal庫:http://download.csdn.net/detail/u011638883/6726339

       好了,就這樣,,

       謝謝!!

       update(2013-12-17):補上項目中的Afinal架構代碼,之前上傳了5、6次都失敗,,