Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android自定義AutoScrollViewPager:自動循環滑動頁面

Android自定義AutoScrollViewPager:自動循環滑動頁面

編輯:關於Android編程

---------------------布局頁面----------------------------------------------

android:id="@+id/luck_detail_adv_ContainerRl"
android:layout_width="match_parent"
android:layout_height="match_parent" >

android:id="@+id/luck_detail_Vp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffa1a1a1" />

android:id="@+id/luck_detail_adv_dotLl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="4.5dp"
android:paddingTop="4.5dp" >


 

 

-----------------------------有做修改的AutoScrollViewPager------------------------------------

public class AutoScrollViewPager extends ViewPager {
/**定義頁面點擊事件*/
public interface OnPageItemClickListener {
void onPageItemClickListener(T pd);
}
/**滑動時間間距*/
private int mScrollTime = 0;
/**之前位置*/
private int oldIndex = 0;
/**當前頁面位置*/
private int curIndex = 0;
/**圖片數據集合*/
private List mPagerData = new ArrayList();
/**適配器*/
private PagerAdapter pagerAdapter;
/**圖片下面指示小圓點所在布局*/
private LinearLayout indicatorView;
/**小圓點狀態圖片resId*/
private int focusedDrawable, normalDrawable;
private LayoutInflater inflater;
private OnPageItemClickListener pageItemClickListener;
/**是否是假的循環*/
private boolean isFakeCycle = false;
/**是否開始滾動*/
private boolean isStartScroll;
/**頁面改變監聽*/
private PageChangedCallBack mCallBack;
public interface PageChangedCallBack{
void onPageChange(int position);
}


public AutoScrollViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
inflater = LayoutInflater.from(context);
focusedDrawable = R.drawable.common_dot_selected;
normalDrawable = R.drawable.common_dot_normal;


setInternalPageChangeListener(new OnPageChangeListener() {
public void onPageSelected(int i) {
if(mCallBack!=null)
mCallBack.onPageChange(i);
if (mPagerData.isEmpty() || indicatorView == null || indicatorView.getChildCount() == 0)
return;
curIndex = i % mPagerData.size();
/**取消圓點選中*/
indicatorView.getChildAt(oldIndex).setBackgroundResource(normalDrawable);
/**圓點選中*/
indicatorView.getChildAt(curIndex).setBackgroundResource(focusedDrawable);
oldIndex = curIndex;
}


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


public void onPageScrollStateChanged(int arg0) {
}
});


/**設置滑動動畫時間 ,如果用默認動畫時間可不用 ,反射技術實現*/
new FixedSpeedScroller(getContext()).setDuration(this, 700);


pagerAdapter = new MyPagerAdapter();
setAdapter(pagerAdapter);
/**設置預加載數據量,自己設定*/
setOffscreenPageLimit(2);
/**用requestDisallowInterceptTouchEvent()方法防止viewpager和子view沖突*/
requestDisallowInterceptTouchEvent(true);

options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.index_advert_default) /**加載過程中默認顯示圖片*/
.showImageForEmptyUri(R.drawable.index_advert_default) /**圖片url為空果默認顯示圖片*/
.showImageOnFail(R.drawable.index_advert_default) /**加載錯誤時默認顯示圖片*/
.resetViewBeforeLoading(false).build();
}

public void setPageChangeCallback(PageChangedCallBack clallBack){
mCallBack=clallBack;
}

@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if(isStartScroll){
start(mScrollTime);
}
}

@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if(isStartScroll)
handler.removeCallbacksAndMessages(null);
}


/** 構建內部索引父view */
private void initInnerIndicator() {
indicatorView = new IndicatorView(getContext());
indicatorView.setGravity(Gravity.CENTER);
indicatorView.setBackgroundColor(0x0fFF00FF);
indicatorView.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams params = new LayoutParams();
params.width = ViewGroup.LayoutParams.MATCH_PARENT;
params.height = 40;
params.gravity = Gravity.BOTTOM;
addView(indicatorView, params);
}


public void setDatas(List imgUrls, LinearLayout outIndicator, boolean needInnerIndicator, boolean isFakeCycle) {
this.isFakeCycle = isFakeCycle;
setDatas(imgUrls, outIndicator, needInnerIndicator);
}

/**重復調用可能會anr*/
public void setDatas(List imgUrls, LinearLayout outIndicator, boolean needInnerIndicator) {
if (outIndicator != null) {
indicatorView = outIndicator;
}
else if (needInnerIndicator) {
initInnerIndicator();
}
mPagerData.clear();
mPagerData.addAll(imgUrls);
pagerAdapter.notifyDataSetChanged();
}

/**重新加載圖片數據,刷新vp內容*/
public void refreshDatas(List imgUrls, LinearLayout outIndicator, boolean needInnerIndicator,boolean isFakeCycle) {
this.isFakeCycle = isFakeCycle;
if (outIndicator != null) {
indicatorView = outIndicator;
}
else if (needInnerIndicator) {
initInnerIndicator();
}
mPagerData.clear();
mPagerData.addAll(imgUrls);
pagerAdapter = new MyPagerAdapter();
setAdapter(pagerAdapter);
pagerAdapter.notifyDataSetChanged();
}


@Override
void dataSetChanged() {
super.dataSetChanged();
setUpIndicator();
}


/**設置圓點*/
private void setUpIndicator() {
if (indicatorView != null) {
indicatorView.removeAllViews();
if (mPagerData.isEmpty()) {
indicatorView.setVisibility(View.GONE);
return;
}
else {
indicatorView.setVisibility(View.VISIBLE);
}
for (int i = 0; i < mPagerData.size(); i++) {
View v = inflater.inflate(R.layout.auto_scrollpage_dot, indicatorView, false);
v.setBackgroundResource(normalDrawable);
indicatorView.addView(v);
}
indicatorView.getChildAt(0).setBackgroundResource(focusedDrawable);
}
curIndex = oldIndex = 0;
if (mPagerData.size() > 1 && isFakeCycle) {
setCurrentItem(15 - 15 % mPagerData.size());
}
else {
setCurrentItem(0);
}
}


/** 獲取真實的當前位置 */
public int getCurrentPosition() {
return curIndex;
}


/** 獲取真實的當前位置的數據 */
public T getCurrentData() throws IndexOutOfBoundsException {
return mPagerData.get(curIndex);
}


@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
start();
}
else {
handler.removeCallbacksAndMessages(null);
}
return super.onInterceptTouchEvent(ev);
}


@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
start();
}
else {
handler.removeCallbacksAndMessages(null);
}
return super.onTouchEvent(ev);
}


/** 開始廣告滾動 */
private void start() {
start(mScrollTime);
}


public void start(int scrollTime) {
mScrollTime = scrollTime;
isStartScroll = false;
if (mScrollTime > 0 && !mPagerData.isEmpty()) {
isStartScroll = true;
handler.sendMessageDelayed(handler.obtainMessage(), mScrollTime);
}
}


private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
handler.removeCallbacksAndMessages(null);
if(isFakeCycle){
setCurrentItem(getCurrentItem() + 1);
}else{
if(getCurrentItem() == mPagerData.size()-1){
setCurrentItem(0, true);
}else{
setCurrentItem(getCurrentItem() + 1);
}
}
handler.sendMessageDelayed(handler.obtainMessage(), mScrollTime);
};
};
/**加載網絡圖片,用到了Universal-Image-Loader開源框架*/
private DisplayImageOptions options;

public void setImageOptions(DisplayImageOptions options){
this.options=options;
}


/**ViewPager適配器*/
private class MyPagerAdapter extends PagerAdapter {


@Override
public int getCount() {
if (mPagerData.size() == 1) {
return 1;
}
else if (mPagerData.size() > 1) {
return isFakeCycle ? Integer.MAX_VALUE : mPagerData.size();
}
return 0;
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
final int realP = position % mPagerData.size();
final ImageView netImgView = (ImageView) inflater.inflate(R.layout.auto_scrollpage_img, container, false);
ImageLoader.getInstance().displayImage(mPagerData.get(realP).getImageUrl(), netImgView, options);
netImgView.setOnClickListener(new View.OnClickListener() {


@Override
public void onClick(View v) {
if (pageItemClickListener != null) {
pageItemClickListener.onPageItemClickListener(mPagerData.get(realP));
}
}
});


container.addView(netImgView);
return netImgView;
}


@Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (object instanceof View) {
container.removeView((View) object);
}
}


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


/** 設置顯示條目的點擊事件 */
public void setOnPageItemClickListener(OnPageItemClickListener pageItemClickListener) {
this.pageItemClickListener = pageItemClickListener;
}
}

-----------------內部數據模型,根據需要添加-----------------------------------------


public interface PagerImageData{
public String getImageUrl();/**用於顯示網絡圖片*/
public void setImageUrl(String imgUrl);
}

--------------------在Activity中使用AutoScrollViewPager--------------------------------------------------------

/**圖片展示,ImageBean是項目中用到的請求服務器json數據的實體bean(要繼承PagerImageData) */
private AutoScrollViewPager advertiseVp;

advertiseVp = (AutoScrollViewPager) findViewById(R.id.luck_detail_Vp);

advertiseVp.setOnPageItemClickListener(new OnPageItemClickListener() {
@Override
public void onPageItemClickListener(ImageBean pd) {
//頁面點擊事件,做想做的效果(查看大圖,跳轉到其它地方等)
}
});

/**添加數據imageArray是從服務器取得的圖片url集合,也可以自己准備好List imageArray=new ArrayList(),往裡面加想要的數據*/

advertiseVp.refreshDatas(imageArray, (LinearLayout) findViewById(R.id.luck_detail_adv_dotLl), false, true);
advertiseVp.start(3000);

Activity中的代碼沒有寫全,有時間把項目中用到的整理成個demo上傳上去,注意文章中兩處紅色的地方,我在代碼中簡寫了。

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