Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android實現Banner界面廣告圖片循環輪播(包括實現手動滑動循環)

Android實現Banner界面廣告圖片循環輪播(包括實現手動滑動循環)

編輯:關於Android編程

 前言:經常會看到有一些app的banner界面可以實現循環播放多個廣告圖片和手動滑動循環。本以為單純的ViewPager就可以實現這些功能。但是蛋疼的事情來了,ViewPager並不支持循環翻頁。所以要實現循環還得需要自己去動手。自己在網上也找了些例子,本博文的Demo是結合自己找到的一些相關例子的基礎上去改造,也希望對讀者有用。

Demo實現的效果圖如下:

Demo代碼:

工程目錄如下圖:

廢話不多說,上代碼。

1.主Activity代碼如下:

package com.stevenhu.android.phone.ui; 
import java.util.ArrayList; 
import java.util.List; 
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; 
import com.nostra13.universalimageloader.core.DisplayImageOptions; 
import com.nostra13.universalimageloader.core.ImageLoader; 
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; 
import com.nostra13.universalimageloader.core.assist.QueueProcessingType; 
import com.stevenhu.android.phone.bean.ADInfo; 
import com.stevenhu.android.phone.utils.ViewFactory; 
import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.ImageView; 
import android.widget.Toast; 
import cn.androiddevelop.cycleviewpager.lib.CycleViewPager; 
import cn.androiddevelop.cycleviewpager.lib.CycleViewPager.ImageCycleViewListener; 
/** 
* 描述:主頁 
* 
* @author stevenhu 
* @version 2015年5月8日 上午10:47:37 
*/ 
public class MainActivity extends Activity { 
private List<ImageView> views = new ArrayList<ImageView>(); 
private List<ADInfo> infos = new ArrayList<ADInfo>(); 
private CycleViewPager cycleViewPager; 
private String[] imageUrls = {"http://img.taodiantong.cn/v55183/infoimg/2013-07/130720115322ky.jpg", 
"http://pic30.nipic.com/20130626/8174275_085522448172_2.jpg", 
"http://pic18.nipic.com/20111215/577405_080531548148_2.jpg", 
"http://pic15.nipic.com/20110722/2912365_092519919000_2.jpg", 
"http://pic.58pic.com/58pic/12/64/27/55U58PICrdX.jpg"}; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.ui_main); 
configImageLoader(); 
initialize(); 
} 
@SuppressLint("NewApi") 
private void initialize() { 
cycleViewPager = (CycleViewPager) getFragmentManager() 
.findFragmentById(R.id.fragment_cycle_viewpager_content); 
for(int i = 0; i < imageUrls.length; i ++){ 
ADInfo info = new ADInfo(); 
info.setUrl(imageUrls[i]); 
info.setContent("圖片-->" + i ); 
infos.add(info); 
} 
// 將最後一個ImageView添加進來 
views.add(ViewFactory.getImageView(this, infos.get(infos.size() - 1).getUrl())); 
for (int i = 0; i < infos.size(); i++) { 
views.add(ViewFactory.getImageView(this, infos.get(i).getUrl())); 
} 
// 將第一個ImageView添加進來 
views.add(ViewFactory.getImageView(this, infos.get(0).getUrl())); 
// 設置循環,在調用setData方法前調用 
cycleViewPager.setCycle(true); 
// 在加載數據前設置是否循環 
cycleViewPager.setData(views, infos, mAdCycleViewListener); 
//設置輪播 
cycleViewPager.setWheel(true); 
// 設置輪播時間,默認5000ms 
cycleViewPager.setTime(2000); 
//設置圓點指示圖標組居中顯示,默認靠右 
cycleViewPager.setIndicatorCenter(); 
} 
private ImageCycleViewListener mAdCycleViewListener = new ImageCycleViewListener() { 
@Override 
public void onImageClick(ADInfo info, int position, View imageView) { 
if (cycleViewPager.isCycle()) { 
position = position - 1; 
Toast.makeText(MainActivity.this, 
"position-->" + info.getContent(), Toast.LENGTH_SHORT) 
.show(); 
} 
} 
}; 
/** 
* 配置ImageLoder 
*/ 
private void configImageLoader() { 
// 初始化ImageLoader 
@SuppressWarnings("deprecation") 
DisplayImageOptions options = new DisplayImageOptions.Builder().showStubImage(R.drawable.icon_stub) // 設置圖片下載期間顯示的圖片 
.showImageForEmptyUri(R.drawable.icon_empty) // 設置圖片Uri為空或是錯誤的時候顯示的圖片 
.showImageOnFail(R.drawable.icon_error) // 設置圖片加載或解碼過程中發生錯誤顯示的圖片 
.cacheInMemory(true) // 設置下載的圖片是否緩存在內存中 
.cacheOnDisc(true) // 設置下載的圖片是否緩存在SD卡中 
// .displayer(new RoundedBitmapDisplayer(20)) // 設置成圓角圖片 
.build(); // 創建配置過得DisplayImageOption對象 
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).defaultDisplayImageOptions(options) 
.threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory() 
.discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build(); 
ImageLoader.getInstance().init(config); 
} 
} 

2.主文件ui_main.xml代碼如下:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 
<fragment 
android:id="@+id/fragment_cycle_viewpager_content" 
android:name="cn.androiddevelop.cycleviewpager.lib.CycleViewPager" 
android:layout_width="match_parent" 
android:layout_height="180dip" /> 
<RelativeLayout 
android:layout_width="fill_parent" 
android:layout_height="0dip" 
android:layout_weight="1"> 
<TextView 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_centerInParent="true" 
android:text="content"/> 
</RelativeLayout> 
</LinearLayout> 

3.CycleViewPager類代碼如下:

package cn.androiddevelop.cycleviewpager.lib; 
import java.util.ArrayList; 
import java.util.List; 
import android.annotation.SuppressLint; 
import android.app.Fragment; 
import android.os.Bundle; 
import android.os.Message; 
import android.support.v4.view.PagerAdapter; 
import android.support.v4.view.ViewPager.OnPageChangeListener; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.FrameLayout; 
import android.widget.ImageView; 
import android.widget.LinearLayout; 
import android.widget.RelativeLayout; 
import com.stevenhu.android.phone.bean.ADInfo; 
import com.stevenhu.android.phone.ui.R; 
/** 
* 實現可循環,可輪播的viewpager 
*/ 
@SuppressLint("NewApi") 
public class CycleViewPager extends Fragment implements OnPageChangeListener { 
private List<ImageView> imageViews = new ArrayList<ImageView>(); 
private ImageView[] indicators; 
private FrameLayout viewPagerFragmentLayout; 
private LinearLayout indicatorLayout; // 指示器 
private BaseViewPager viewPager; 
private BaseViewPager parentViewPager; 
private ViewPagerAdapter adapter; 
private CycleViewPagerHandler handler; 
private int time = 5000; // 默認輪播時間 
private int currentPosition = 0; // 輪播當前位置 
private boolean isScrolling = false; // 滾動框是否滾動著 
private boolean isCycle = false; // 是否循環 
private boolean isWheel = false; // 是否輪播 
private long releaseTime = 0; // 手指松開、頁面不滾動時間,防止手機松開後短時間進行切換 
private int WHEEL = 100; // 轉動 
private int WHEEL_WAIT = 101; // 等待 
private ImageCycleViewListener mImageCycleViewListener; 
private List<ADInfo> infos; 
@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState) { 
View view = LayoutInflater.from(getActivity()).inflate( 
R.layout.view_cycle_viewpager_contet, null); 
viewPager = (BaseViewPager) view.findViewById(R.id.viewPager); 
indicatorLayout = (LinearLayout) view 
.findViewById(R.id.layout_viewpager_indicator); 
viewPagerFragmentLayout = (FrameLayout) view 
.findViewById(R.id.layout_viewager_content); 
handler = new CycleViewPagerHandler(getActivity()) { 
@Override 
public void handleMessage(Message msg) { 
super.handleMessage(msg); 
if (msg.what == WHEEL && imageViews.size() != 0) { 
if (!isScrolling) { 
int max = imageViews.size() + 1; 
int position = (currentPosition + 1) % imageViews.size(); 
viewPager.setCurrentItem(position, true); 
if (position == max) { // 最後一頁時回到第一頁 
viewPager.setCurrentItem(1, false); 
} 
} 
releaseTime = System.currentTimeMillis(); 
handler.removeCallbacks(runnable); 
handler.postDelayed(runnable, time); 
return; 
} 
if (msg.what == WHEEL_WAIT && imageViews.size() != 0) { 
handler.removeCallbacks(runnable); 
handler.postDelayed(runnable, time); 
} 
} 
}; 
return view; 
} 
public void setData(List<ImageView> views, List<ADInfo> list, ImageCycleViewListener listener) { 
setData(views, list, listener, 0); 
} 
/** 
* 初始化viewpager 
* 
* @param views 
* 要顯示的views 
* @param showPosition 
* 默認顯示位置 
*/ 
public void setData(List<ImageView> views, List<ADInfo> list, ImageCycleViewListener listener, int showPosition) { 
mImageCycleViewListener = listener; 
infos = list; 
this.imageViews.clear(); 
if (views.size() == 0) { 
viewPagerFragmentLayout.setVisibility(View.GONE); 
return; 
} 
for (ImageView item : views) { 
this.imageViews.add(item); 
} 
int ivSize = views.size(); 
// 設置指示器 
indicators = new ImageView[ivSize]; 
if (isCycle) 
indicators = new ImageView[ivSize - 2]; 
indicatorLayout.removeAllViews(); 
for (int i = 0; i < indicators.length; i++) { 
View view = LayoutInflater.from(getActivity()).inflate( 
R.layout.view_cycle_viewpager_indicator, null); 
indicators[i] = (ImageView) view.findViewById(R.id.image_indicator); 
indicatorLayout.addView(view); 
} 
adapter = new ViewPagerAdapter(); 
// 默認指向第一項,下方viewPager.setCurrentItem將觸發重新計算指示器指向 
setIndicator(0); 
viewPager.setOffscreenPageLimit(3); 
viewPager.setOnPageChangeListener(this); 
viewPager.setAdapter(adapter); 
if (showPosition < 0 || showPosition >= views.size()) 
showPosition = 0; 
if (isCycle) { 
showPosition = showPosition + 1; 
} 
viewPager.setCurrentItem(showPosition); 
} 
/** 
* 設置指示器居中,默認指示器在右方 
*/ 
public void setIndicatorCenter() { 
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( 
RelativeLayout.LayoutParams.WRAP_CONTENT, 
RelativeLayout.LayoutParams.WRAP_CONTENT); 
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); 
params.addRule(RelativeLayout.CENTER_HORIZONTAL); 
indicatorLayout.setLayoutParams(params); 
} 
/** 
* 是否循環,默認不開啟,開啟前,請將views的最前面與最後面各加入一個視圖,用於循環 
* 
* @param isCycle 
* 是否循環 
*/ 
public void setCycle(boolean isCycle) { 
this.isCycle = isCycle; 
} 
/** 
* 是否處於循環狀態 
* 
* @return 
*/ 
public boolean isCycle() { 
return isCycle; 
} 
/** 
* 設置是否輪播,默認不輪播,輪播一定是循環的 
* 
* @param isWheel 
*/ 
public void setWheel(boolean isWheel) { 
this.isWheel = isWheel; 
isCycle = true; 
if (isWheel) { 
handler.postDelayed(runnable, time); 
} 
} 
/** 
* 是否處於輪播狀態 
* 
* @return 
*/ 
public boolean isWheel() { 
return isWheel; 
} 
final Runnable runnable = new Runnable() { 
@Override 
public void run() { 
if (getActivity() != null && !getActivity().isFinishing() 
&& isWheel) { 
long now = System.currentTimeMillis(); 
// 檢測上一次滑動時間與本次之間是否有觸擊(手滑動)操作,有的話等待下次輪播 
if (now - releaseTime > time - 500) { 
handler.sendEmptyMessage(WHEEL); 
} else { 
handler.sendEmptyMessage(WHEEL_WAIT); 
} 
} 
} 
}; 
/** 
* 釋放指示器高度,可能由於之前指示器被限制了高度,此處釋放 
*/ 
public void releaseHeight() { 
getView().getLayoutParams().height = RelativeLayout.LayoutParams.MATCH_PARENT; 
refreshData(); 
} 
/** 
* 設置輪播暫停時間,即沒多少秒切換到下一張視圖.默認5000ms 
* 
* @param time 
* 毫秒為單位 
*/ 
public void setTime(int time) { 
this.time = time; 
} 
/** 
* 刷新數據,當外部視圖更新後,通知刷新數據 
*/ 
public void refreshData() { 
if (adapter != null) 
adapter.notifyDataSetChanged(); 
} 
/** 
* 隱藏CycleViewPager 
*/ 
public void hide() { 
viewPagerFragmentLayout.setVisibility(View.GONE); 
} 
/** 
* 返回內置的viewpager 
* 
* @return viewPager 
*/ 
public BaseViewPager getViewPager() { 
return viewPager; 
} 
/** 
* 頁面適配器 返回對應的view 
* 
* @author Yuedong Li 
* 
*/ 
private class ViewPagerAdapter extends PagerAdapter { 
@Override 
public int getCount() { 
return imageViews.size(); 
} 
@Override 
public boolean isViewFromObject(View arg0, Object arg1) { 
return arg0 == arg1; 
} 
@Override 
public void destroyItem(ViewGroup container, int position, Object object) { 
container.removeView((View) object); 
} 
@Override 
public View instantiateItem(ViewGroup container, final int position) { 
ImageView v = imageViews.get(position); 
if (mImageCycleViewListener != null) { 
v.setOnClickListener(new OnClickListener() { 
@Override 
public void onClick(View v) { 
mImageCycleViewListener.onImageClick(infos.get(currentPosition - 1), currentPosition, v); 
} 
}); 
} 
container.addView(v); 
return v; 
} 
@Override 
public int getItemPosition(Object object) { 
return POSITION_NONE; 
} 
} 
@Override 
public void onPageScrollStateChanged(int arg0) { 
if (arg0 == 1) { // viewPager在滾動 
isScrolling = true; 
return; 
} else if (arg0 == 0) { // viewPager滾動結束 
if (parentViewPager != null) 
parentViewPager.setScrollable(true); 
releaseTime = System.currentTimeMillis(); 
viewPager.setCurrentItem(currentPosition, false); 
} 
isScrolling = false; 
} 
@Override 
public void onPageScrolled(int arg0, float arg1, int arg2) { 
} 
@Override 
public void onPageSelected(int arg0) { 
int max = imageViews.size() - 1; 
int position = arg0; 
currentPosition = arg0; 
if (isCycle) { 
if (arg0 == 0) { 
currentPosition = max - 1; 
} else if (arg0 == max) { 
currentPosition = 1; 
} 
position = currentPosition - 1; 
} 
setIndicator(position); 
} 
/** 
* 設置viewpager是否可以滾動 
* 
* @param enable 
*/ 
public void setScrollable(boolean enable) { 
viewPager.setScrollable(enable); 
} 
/** 
* 返回當前位置,循環時需要注意返回的position包含之前在views最前方與最後方加入的視圖,即當前頁面試圖在views集合的位置 
* 
* @return 
*/ 
public int getCurrentPostion() { 
return currentPosition; 
} 
/** 
* 設置指示器 
* 
* @param selectedPosition 
* 默認指示器位置 
*/ 
private void setIndicator(int selectedPosition) { 
for (int i = 0; i < indicators.length; i++) { 
indicators[i] 
.setBackgroundResource(R.drawable.icon_point); 
} 
if (indicators.length > selectedPosition) 
indicators[selectedPosition] 
.setBackgroundResource(R.drawable.icon_point_pre); 
} 
/** 
* 如果當前頁面嵌套在另一個viewPager中,為了在進行滾動時阻斷父ViewPager滾動,可以 阻止父ViewPager滑動事件 
* 父ViewPager需要實現ParentViewPager中的setScrollable方法 
*/ 
public void disableParentViewPagerTouchEvent(BaseViewPager parentViewPager) { 
if (parentViewPager != null) 
parentViewPager.setScrollable(false); 
} 
/** 
* 輪播控件的監聽事件 
* 
* @author minking 
*/ 
public static interface ImageCycleViewListener { 
/** 
* 單擊圖片事件 
* 
* @param position 
* @param imageView 
*/ 
public void onImageClick(ADInfo info, int postion, View imageView); 
} 
}

CycleViewPager類為實現可循環,可輪播的ViewPager的核心類,繼承自Fragment,具體實現原理就不多說了,代碼中都有相關的注釋。

以上所述是小編給大家介紹的Android實現Banner界面廣告圖片循環輪播(包括實現手動滑動循環),希望對大家有所幫助!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved