如德芙般丝滑的ViewPager轮播

每次在地铁上把玩别的应用时,看着别人家的轮播图总是那么高大上,滑动起来总是那么衔接完美,就像别人家的亚索和盲僧总是那么6。我不服,solo,于是当即也手动写一个。
Talk is cheap,show you the code

Talk is cheap,show you the effect:


如德芙般丝滑的ViewPager轮播_第1张图片
giphy.gif

功能简介:

自定义的一个BannerView轮播器类,实现可滑动指示点,可调节滑动速度;

实现步骤:

1.BannerView引入布局:viewpager显示轮播,linearlayout用于添加一排白色(未选中状态)小圆点,view用于显示红色移动小圆点。



    

    

        

        
    

2.viewpager的pageradapter类,每一项为imageview,实现多张切换。

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class BannerViewpagerAdapter extends PagerAdapter {
    private Context context;
    private int[] pics;

    public BannerViewpagerAdapter(Context context, int[] pics) {
        this.context = context;
        this.pics = pics;
    }

    @Override
    public int getCount() {
        return Integer.MAX_VALUE;
    }

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

    /**
     * 相当于baseadapter的getview
     * @param container
     * @param position
     * @return
     */
    @Override
    public Object instantiateItem(final ViewGroup container, final int position) {
        ImageView imageView = new ImageView(context);
        container.addView(imageView);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setImageResource(pics[position%pics.length]);

        return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView((View) object);
    }
}
Bannerview类中:

3.初始化,包括初始化自动轮播时间,圆点直径,原点间隙,圆点之间圆心间距(算偏移量)。params1第一个点无左间距,params2其余点有左间距。

    private Context context;
    private ViewPager viewPager;
    public PagerAdapter pagerAdapter;
    /** 自动轮播时间间隔 */
    private final int DELAY_TIME = 4000;
    /** 页面滚动时间 */
    private final int SCROLL_TIME = 400;
    public LinearLayout linearLayout;
    private View bannerView;
    private int[] pics;
    private final int SCROLL_WHAT = 0;
    private LinearLayout.LayoutParams params1,params2;
    private View moveDot;
    /** 相邻点圆心距离 */
    private int dotDistance;
    /** 圆点直径 */
    private int dotDiameter;
    /** 圆之间间隔空隙 */
    private int dotSpace;

    public BannerView(Context context,int[] pics,PagerAdapter pagerAdapter,int layout){
        this.context = context;
        this.pics = pics;
        this.pagerAdapter = pagerAdapter;
        bannerView = LayoutInflater.from(context).inflate(layout,null);
        initView();
        event();
    }

    private void initView() {
        linearLayout = bannerView.findViewById(R.id.dot_linear);
        viewPager = bannerView.findViewById(R.id.viewpager);
        moveDot = bannerView.findViewById(R.id.movedot);
        //设置默认viewpager当前项
        viewPager.setCurrentItem(pics.length*Integer.MAX_VALUE/2);
        viewPager.setAdapter(pagerAdapter);
        pagerAdapter.notifyDataSetChanged();
        handler.sendEmptyMessageDelayed(SCROLL_WHAT, DELAY_TIME);

        dotSpace = dp2px(7);
        dotDiameter = dp2px(6);
        dotDistance = dotDiameter + dotSpace;

        params1 = new LinearLayout.LayoutParams(dotDiameter,dotDiameter);
        params1.leftMargin = 0;
        params2 = new LinearLayout.LayoutParams(dotDiameter,dotDiameter);
        params2.leftMargin = dotSpace;

        setViewPagerDuration();
        initDot();
    }

4.创建白色小圆点,并添加到linearlayout中,第一个无左边界,其余加入左边界。

    /**
     * 创建小圆点
     */
    private void initDot(){
        View dot;
        for(int i=0;i

5.实现移动小红点指示点:
pageChangeListener的onPageScrolled回调方法中,回调了positionOffset值,即滑动当前一页的偏移百分比,范围[0-1]。可以根据实时设置小红点params.leftMargin达到移动效果。那么当前左边距是多少呢。比如滑动到第二和第三页之间,那么左边距就是第一个点和第二个点的间隔dotDistance加上第二和第三点之间偏移乘以dotDistance。


如德芙般丝滑的ViewPager轮播_第2张图片
滑动过程演示
    private void event(){
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) moveDot.getLayoutParams();

                //取余,不然会一直往右移动
                int dotPos = position % pics.length;
                //dotDistance圆心间距
                params.leftMargin = (int) (dotDistance * dotPos + dotDistance * positionOffset);
                moveDot.setLayoutParams(params);
            }

            @Override
            public void onPageSelected(int i) {
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });

    }

6.实现自设置滚动速度:
要设置滚动,滚动事件来自于viewPager.setCurrentItem(),那么顺藤摸瓜,点进setCurrentItem往上找:

    /**
     * Set the currently selected page. If the ViewPager has already been through its first
     * layout with its current adapter there will be a smooth animated transition between
     * the current item and the specified item.
     *
     * @param item Item index to select
     */
    public void setCurrentItem(int item) {
        mPopulatePending = false;
        setCurrentItemInternal(item, !mFirstLayout, false);
    }

实现来自setCurrentItemInternal(),点进去继续,来到了ViewPager类中。从setCurrentItemInternal() -> scrollToItem() -> smoothScrollTo(),里面最终是由mScroller.startScroll(sx, sy, dx, dy, duration)实现了滚动。所以我们要改变duration这个值,一不做二不休,采用偷梁换柱,自己Scroller类,覆写startScroll()方法,传入自己的duration。mScroller是Viewpager的一个成员变量,那就用反射替用自己scroller换掉原有的mScroller。

    void setCurrentItemInternal(int item, boolean smoothScroll, boolean always) {
        setCurrentItemInternal(item, smoothScroll, always, 0);
    }

    void setCurrentItemInternal(int item, boolean smoothScroll, boolean always, int velocity) {
        if (mAdapter == null || mAdapter.getCount() <= 0) {
            setScrollingCacheEnabled(false);
            return;
        }
        if (!always && mCurItem == item && mItems.size() != 0) {
            setScrollingCacheEnabled(false);
            return;
        }

        if (item < 0) {
            item = 0;
        } else if (item >= mAdapter.getCount()) {
            item = mAdapter.getCount() - 1;
        }
        final int pageLimit = mOffscreenPageLimit;
        if (item > (mCurItem + pageLimit) || item < (mCurItem - pageLimit)) {
            // We are doing a jump by more than one page.  To avoid
            // glitches, we want to keep all current pages in the view
            // until the scroll ends.
            for (int i = 0; i < mItems.size(); i++) {
                mItems.get(i).scrolling = true;
            }
        }
        final boolean dispatchSelected = mCurItem != item;

        if (mFirstLayout) {
            // We don't have any idea how big we are yet and shouldn't have any pages either.
            // Just set things up and let the pending layout handle things.
            mCurItem = item;
            if (dispatchSelected) {
                dispatchOnPageSelected(item);
            }
            requestLayout();
        } else {
            populate(item);
            scrollToItem(item, smoothScroll, velocity, dispatchSelected);
        }
    }

private void scrollToItem(int item, boolean smoothScroll, int velocity,
            boolean dispatchSelected) {
        final ItemInfo curInfo = infoForPosition(item);
        int destX = 0;
        if (curInfo != null) {
            final int width = getClientWidth();
            destX = (int) (width * Math.max(mFirstOffset,
                    Math.min(curInfo.offset, mLastOffset)));
        }
        if (smoothScroll) {
            smoothScrollTo(destX, 0, velocity);
            if (dispatchSelected) {
                dispatchOnPageSelected(item);
            }
        } else {
            if (dispatchSelected) {
                dispatchOnPageSelected(item);
            }
            completeScroll(false);
            scrollTo(destX, 0);
            pageScrolled(destX);
        }
    }

7.创建Scroller传入duration覆写startScroll,通过反射取得mScroller属性重设mScroller。

private void setViewPagerDuration(){
        try {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            field.set(viewPager,getScroller(SCROLL_TIME));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private Scroller getScroller(final int smoothDuration){
        Scroller scroller = new Scroller(context,new AccelerateInterpolator()){
            @Override
            public void startScroll(int startX, int startY, int dx, int dy, int duration) {
                super.startScroll(startX, startY, dx, dy, smoothDuration);
            }
        };
        return scroller;
    }
好了,大功告成。完整Bannerview类:
blic class BannerView {
    private Context context;
    private ViewPager viewPager;
    public PagerAdapter pagerAdapter;
    /** 自动轮播时间间隔 */
    private final int DELAY_TIME = 4000;
    /** 页面滚动时间 */
    private final int SCROLL_TIME = 400;
    public LinearLayout linearLayout;
    private View bannerView;
    private int[] pics;
    private final int SCROLL_WHAT = 0;
    private LinearLayout.LayoutParams params1,params2;
    private View moveDot;
    /** 相邻点圆心距离 */
    private int dotDistance;
    /** 圆点直径 */
    private int dotDiameter;
    /** 圆之间间隔空隙 */
    private int dotSpace;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            handler.sendEmptyMessageDelayed(SCROLL_WHAT,DELAY_TIME);
        }
    };

    public BannerView(Context context,int[] pics,PagerAdapter pagerAdapter,int layout){
        this.context = context;
        this.pics = pics;
        this.pagerAdapter = pagerAdapter;
        bannerView = LayoutInflater.from(context).inflate(layout,null);
        initView();
        event();
    }

    private void initView() {
        linearLayout = bannerView.findViewById(R.id.dot_linear);
        viewPager = bannerView.findViewById(R.id.viewpager);
        moveDot = bannerView.findViewById(R.id.movedot);
        //设置默认viewpager当前项
        viewPager.setCurrentItem(pics.length*Integer.MAX_VALUE/2);
        viewPager.setAdapter(pagerAdapter);
        pagerAdapter.notifyDataSetChanged();
        handler.sendEmptyMessageDelayed(SCROLL_WHAT, DELAY_TIME);

        dotSpace = dp2px(7);
        dotDiameter = dp2px(6);
        dotDistance = dotDiameter + dotSpace;

        params1 = new LinearLayout.LayoutParams(dotDiameter,dotDiameter);
        params1.leftMargin = 0;
        params2 = new LinearLayout.LayoutParams(dotDiameter,dotDiameter);
        params2.leftMargin = dotSpace;

        setViewPagerDuration();
        initDot();
    }

    private void event(){
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) moveDot.getLayoutParams();

                //取余,不然会一直往右移动
                int dotPos = position % pics.length;
                params.leftMargin = (int) (dotDistance * dotPos + dotDistance * positionOffset);
                moveDot.setLayoutParams(params);
            }

            @Override
            public void onPageSelected(int i) {
            }

            @Override
            public void onPageScrollStateChanged(int i) {
            }
        });

    }

    /**
     * 创建小圆点
     */
    private void initDot(){
        View dot;
        for(int i=0;i

MainActivity类:

public class MainActivity extends AppCompatActivity {
    private BannerView bannerView;
    private BannerViewpagerAdapter pagerAdapter;
    private RelativeLayout rlBanner;
    private int[] pics = new int[]{R.mipmap.banner1,R.mipmap.banner2,R.mipmap.banner3,R.mipmap.banner4};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
        rlBanner = (RelativeLayout) findViewById(R.id.rl_banner);
        pagerAdapter = new BannerViewpagerAdapter(getApplicationContext(),pics);
        bannerView = new BannerView(getApplicationContext(),pics,pagerAdapter,R.layout.customviewpager);
        //将bannerview添加到需引入控件即可
        rlBanner.addView(bannerView.getBannerView());
    }
}

重要的是想到找到滑动偏移和设置时间的办法,在实际做项目中,办法总比困难多。1000个读者就有1000个林黛玉,那么1000个程序猿就有1000个方法。

你可能感兴趣的:(如德芙般丝滑的ViewPager轮播)