android.support.v4.view.AutoScrollViewPager.java Source code

Java tutorial

Introduction

Here is the source code for android.support.v4.view.AutoScrollViewPager.java

Source

package android.support.v4.view;

import android.content.Context;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
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.vstecs.android.uiframework.R;
import com.vstecs.android.uiframework.view.ImageManager;

import java.util.ArrayList;
import java.util.List;

/**
 * @description
 * @T
 * @date 2014714 ?5:44:17
 * @date 2014715 ?19, fanxing
 */
public class AutoScrollViewPager<T extends PagerData> extends ViewPager {
    public interface OnPageItemClickListener<T extends PagerData> {
        void onPageItemClickListener(T pd, int position);
    }

    private int mScrollTime = 0;
    private int oldIndex = 0;
    private int curIndex = 0;

    private List<T> mPagerData = new ArrayList<T>();
    private PagerAdapter pagerAdapter;
    private LinearLayout indicatorView;
    private int focusedDrawable, normalDrawable;
    private LayoutInflater inflater;
    private OnPageItemClickListener<T> pageItemClickListener;
    private boolean isFakeCycle = false;//??
    private boolean isStartScroll;
    private Context context;

    public AutoScrollViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        inflater = LayoutInflater.from(context);

        focusedDrawable = R.drawable.v4_common_dot_selected;
        normalDrawable = R.drawable.v4_common_dot_normal;

        setInternalPageChangeListener(new OnPageChangeListener() {
            public void onPageSelected(int 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 android.support.v4.view.FixedSpeedScroller(getContext()).setDuration(this, 700);

        pagerAdapter = new MyPagerAdapter();
        setAdapter(pagerAdapter);

        setOffscreenPageLimit(2);

        requestDisallowInterceptTouchEvent(true);

        //      options = new DisplayImageOptions.Builder().showImageOnLoading(R.drawable.ic_launcher) // resource or drawable
        //            .showImageForEmptyUri(R.drawable.ic_launcher) // resource or drawable
        //            .showImageOnFail(R.drawable.ic_launcher) // resource or drawable
        //            .cacheInMemory(true)// ?
        //            .cacheOnDisk(true) // ?
        //            .resetViewBeforeLoading(false).build();
    }

    //
    public void setDotDrawble(int focusedDrawable, int normalDrawable) {
        this.focusedDrawable = focusedDrawable;
        this.normalDrawable = normalDrawable;
    }

    @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 android.support.v4.view.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<T> imgUrls, LinearLayout outIndicator, boolean needInnerIndicator,
            boolean isFakeCycle) {
        this.isFakeCycle = isFakeCycle;
        setDatas(imgUrls, outIndicator, needInnerIndicator);
    }

    /**
     * ???anr
     */
    public void setDatas(List<T> 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<T> 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.v4_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());// /0
        } 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) {
        //      handler.removeCallbacksAndMessages(null);
        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);
        }

        ;
    };

    //   private int errorImageResId=R.drawable.product_list_default;
    //   private int defaultImageResId=R.drawable.product_list_default;
    //   private DisplayImageOptions options;

    //   public void setErrorImageResId(int errorImageResId){
    //      this.errorImageResId=errorImageResId;
    //   }
    //   public void setDefaultImageResId(int defaultImageResId){
    //      this.defaultImageResId=defaultImageResId;
    //   }
    //   public void setImageOptions(DisplayImageOptions options){
    //      this.options=options;
    //   }

    // ? //
    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.v4_scrollpage_img, container, false);

            //ImageLoader
            //         ImageLoader imageLoader = ImageLoader.getInstance();
            //         //ImageLoader?
            //         imageLoader.init(ImageLoaderConfiguration.createDefault(context));
            //         ImageLoader.getInstance().displayImage(mPagerData.get(realP).getImageUrl(), netImgView,options);
            ImageManager.loadImage(netImgView, mPagerData.get(realP).getImageUrl());

            netImgView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (pageItemClickListener != null) {
                        pageItemClickListener.onPageItemClickListener(mPagerData.get(realP), 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<T> pageItemClickListener) {
        this.pageItemClickListener = pageItemClickListener;
    }
}