前言:經常會看到有一些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介面廣告圖片迴圈輪播(包括實現手動滑動迴圈),希望對大家有所協助!