廣告圖片自動輪播控件

自定義廣告輪播java

  • 自定義控件ImageCycleView
  • 每一個廣告頁的對象(包含具體顯示圖片、內容、id等)

    自定義廣告控件 ImageCycleView

package com.changyu.ccfunding.ui.widget;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.changyu.ccfunding.R;
import com.changyu.ccfunding.entity.ADInfo;

import java.util.ArrayList;

/**
 * 廣告圖片自動輪播控件</br>
 * 
 * <pre>
 *   集合ViewPager和指示器的一個輪播控件,主要用於通常常見的廣告圖片輪播,具備自動輪播和手動輪播功能 
 *   使用:只需在xml文件中使用{@code <com.minking.imagecycleview.ImageCycleView/>} ,
 *   而後在頁面中調用  {@link #setImageResources(ArrayList, ImageCycleViewListener) }便可!
 *   
 *   另外提供{@link #startImageCycle() } \ {@link #pushImageCycle() }兩種方法,用於在Activity不可見之時節省資源;
 *   由於自動輪播須要進行控制,有利於內存管理
 * </pre>
 * 
 */
public class ImageCycleView extends LinearLayout {

	/**
	 * 上下文
	 */
	private Context mContext;

	/**
	 * 圖片輪播視圖
	 */
	private CycleViewPager mBannerPager = null;

	/**
	 * 滾動圖片視圖適配器
	 */
	private ImageCycleAdapter mAdvAdapter;

	/**
	 * 圖片輪播指示器控件
	 */
	private ViewGroup mGroup;

	/**
	 * 圖片輪播指示器-個圖
	 */
	private ImageView mImageView = null;

	/**
	 * 滾動圖片指示器-視圖列表
	 */
	private ImageView[] mImageViews = null;

	/**
	 * 圖片滾動當前圖片下標
	 */
	private int mImageIndex = 1;

	/**
	 * 手機密度
	 */
	private float mScale;

	/**
	 * @param context
	 */
	public ImageCycleView(Context context) {
		super(context);
	}

	/**
	 * @param context
	 * @param attrs
	 */
	public ImageCycleView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		mScale = context.getResources().getDisplayMetrics().density;
		LayoutInflater.from(context).inflate(R.layout.view_banner_content, this);
		mBannerPager = (CycleViewPager) findViewById(R.id.pager_banner);
		mBannerPager.setOnPageChangeListener(new GuidePageChangeListener());
		mBannerPager.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
					case MotionEvent.ACTION_UP:
						// 開始圖片滾動
						startImageTimerTask();
						break;
					default:
						// 中止圖片滾動
						stopImageTimerTask();
						break;
				}
				return false;
			}
		});
		// 滾動圖片右下指示器視圖
		mGroup = (ViewGroup) findViewById(R.id.viewGroup);
	}

	/**
	 * 裝填圖片數據
	 * 
	 * @param infoList
	 * @param imageCycleViewListener
	 */
	public void setImageResources(ArrayList<ADInfo> infoList, ImageCycleViewListener imageCycleViewListener) {
		// 清除全部子視圖
		mGroup.removeAllViews();
		// 圖片廣告數量
		final int imageCount = infoList.size();
		mImageViews = new ImageView[imageCount];
		for (int i = 0; i < imageCount; i++) {
			mImageView = new ImageView(mContext);
			int imageParams = (int) (mScale * 20 + 0.5f);// XP與DP轉換,適應不一樣分辨率
			int imagePadding = (int) (mScale * 5 + 0.5f);
			LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			layout.setMargins(3, 0, 3, 0);
			mImageView.setLayoutParams(layout);
			//mImageView.setPadding(imagePadding, imagePadding, imagePadding, imagePadding);
			mImageViews[i] = mImageView;
			if (i == 0) {
				mImageViews[i].setBackgroundResource(R.drawable.icon_point_pre);
			} else {
				mImageViews[i].setBackgroundResource(R.drawable.icon_point);
			}
			mGroup.addView(mImageViews[i]);
		}
		mAdvAdapter = new ImageCycleAdapter(mContext, infoList, imageCycleViewListener);
		mBannerPager.setAdapter(mAdvAdapter);
		startImageTimerTask();
	}

	/**
	 * 開始輪播(手動控制自動輪播與否,便於資源控制)
	 */
	public void startImageCycle() {
		startImageTimerTask();
	}

	/**
	 * 暫停輪播——用於節省資源
	 */
	public void pushImageCycle() {
		stopImageTimerTask();
	}

	/**
	 * 開始圖片滾動任務
	 */
	private void startImageTimerTask() {
		stopImageTimerTask();
		// 圖片每3秒滾動一次
		mHandler.postDelayed(mImageTimerTask, 3000);
	}

	/**
	 * 中止圖片滾動任務
	 */
	private void stopImageTimerTask() {
		mHandler.removeCallbacks(mImageTimerTask);
	}

	private Handler mHandler = new Handler();

	/**
	 * 圖片自動輪播Task
	 */
	private Runnable mImageTimerTask = new Runnable() {

		@Override
		public void run() {
			if (mImageViews != null) {
				// 下標等於圖片列表長度說明已滾動到最後一張圖片,重置下標
				if ((++mImageIndex) == mImageViews.length + 1) {
					mImageIndex = 1;
				}
				mBannerPager.setCurrentItem(mImageIndex);
			}
		}
	};

	/**
	 * 輪播圖片狀態監聽器
	 * 
	 * @author minking
	 */
	private final class GuidePageChangeListener implements OnPageChangeListener {

		@Override
		public void onPageScrollStateChanged(int state) {
			if (state == ViewPager.SCROLL_STATE_IDLE)
				startImageTimerTask(); // 開始下次計時
		}

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

		@Override
		public void onPageSelected(int index) {
			
			if (index == 0 || index == mImageViews.length + 1) {
				return;
			}
			// 設置圖片滾動指示器背景
			mImageIndex = index;
			index -= 1;
			mImageViews[index].setBackgroundResource(R.drawable.icon_point_pre);
			for (int i = 0; i < mImageViews.length; i++) {
				if (index != i) {
					mImageViews[i].setBackgroundResource(R.drawable.icon_point);
				}
			}

		}

	}

	private class ImageCycleAdapter extends PagerAdapter {

		/**
		 * 圖片視圖緩存列表
		 */
		private ArrayList<ImageView> mImageViewCacheList;

		/**
		 * 圖片資源列表
		 */
		private ArrayList<ADInfo> mAdList = new ArrayList<ADInfo>();

		/**
		 * 廣告圖片點擊監聽器
		 */
		private ImageCycleViewListener mImageCycleViewListener;

		private Context mContext;

		public ImageCycleAdapter(Context context, ArrayList<ADInfo> adList, ImageCycleViewListener imageCycleViewListener) {
			mContext = context;
			mAdList = adList;
			mImageCycleViewListener = imageCycleViewListener;
			mImageViewCacheList = new ArrayList<ImageView>();
		}

		@Override
		public int getCount() {
			return mAdList.size();
		}

		@Override
		public boolean isViewFromObject(View view, Object obj) {
			return view == obj;
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			String imageUrl = mAdList.get(position).getUrl();
			ImageView imageView = null;
			if (mImageViewCacheList.isEmpty()) {
				imageView = new ImageView(mContext);
				imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
				imageView.setScaleType(ImageView.ScaleType.FIT_XY);
				
			} else {
				imageView = mImageViewCacheList.remove(0);
			}
			// 設置圖片點擊監聽
			imageView.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					mImageCycleViewListener.onImageClick(mAdList.get(position),position, v);
				}
			});
			imageView.setTag(imageUrl);
			container.addView(imageView);
			mImageCycleViewListener.displayImage(imageUrl, imageView);
			return imageView;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			ImageView view = (ImageView) object;
			container.removeView(view);
			mImageViewCacheList.add(view);
		}

	}

	/**
	 * 輪播控件的監聽事件
	 * 
	 * @author minking
	 */
	public static interface ImageCycleViewListener {

		/**
		 * 加載圖片資源
		 * 
		 * @param imageURL
		 * @param imageView
		 */
		public void displayImage(String imageURL, ImageView imageView);

		/**
		 * 單擊圖片事件
		 * 
		 * @param info
		 * @param imageView
		 */
		public void onImageClick(ADInfo info, int postion, View imageView);
	}

}

 


每一個廣告頁的對象

package com.changyu.ccfunding.entity;

/**
 * 描述:廣告信息</br>
 *
 * @author Eden Cheng</br>
 * @version 2015年4月23日 上午11:32:53
 */
public class ADInfo {
    String id = "";
    String url = "";
    String content = "";
    String type = "";

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

}

 


主函數FirstFragment.java

  • 填充Arrylist<ADinfo>數組
  • 實現ImageCycleView控件中的ImageCycleViewListener監聽(其中包括每一頁的點擊事件和圖片加載(Pcasso圖片加載))
package com.changyu.ccfunding.ui.fragment;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.changyu.ccfunding.R;
import com.changyu.ccfunding.entity.ADInfo;
import com.changyu.ccfunding.ui.base.BaseFragment;
import com.changyu.ccfunding.ui.widget.ImageCycleView;
import com.changyu.ccfunding.ui.widget.ImageCycleView.ImageCycleViewListener;
import com.squareup.picasso.Picasso;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;

/**
 * Created by Administrator on 2016/7/11.
 */

@ContentView(R.layout.fragment_first)
public class FirstFragment extends BaseFragment {


    @ViewInject(R.id.ad_view)
    private ImageCycleView mAdView;

    private ArrayList<ADInfo> infos = new ArrayList<ADInfo>();

    private String[] imageUrls = {"http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg",
            "http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg",
            "http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg",
            "http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg",
            "http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg",};


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        for (int i = 0; i < imageUrls.length; i++) {
            ADInfo info = new ADInfo();
            info.setUrl(imageUrls[i]);
            info.setContent("top-->" + i);
            infos.add(info);
        }
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mAdView.setImageResources(infos, mAdCycleViewListener);
    }


    private ImageCycleViewListener mAdCycleViewListener = new ImageCycleViewListener() {

        @Override
        public void onImageClick(ADInfo info, int position, View imageView) {
            Toast.makeText(getActivity(), "content->" + info.getContent(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void displayImage(String imageURL, ImageView imageView) {

            Picasso.with(getActivity()).load(imageURL).into(imageView);
//            ImageLoader.getInstance().displayImage(imageURL, imageView);// 使用ImageLoader對圖片進行加裝!

        }
    };


    @Override
    public void onResume() {
        super.onResume();
        mAdView.startImageCycle();
    }

    @Override
    public void onPause() {
        super.onPause();
        mAdView.pushImageCycle();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mAdView.pushImageCycle();
    }
}
相關文章
相關標籤/搜索