LoopViewPager+LoopIndicator

公司有个需求要在引导页增加指示的动态效果,于是臆测着效果应该是这样:
臆测图
结果我想多了根本不是这么回事,算了反正有这个想法就做一下试试,本想着只做LoopIndicator后面想了想,如果ViewPager无限滑动的话指引还会指示正确吗????于是乎LoopViewPager也就一起做了。下面是干货:

主布局:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

   <com.example.indicator.Indicator
       android:id="@+id/indicator"
       android:background="#000000"
       android:layout_gravity="bottom"
       android:layout_width="match_parent"
       android:layout_height="50dp"/>
</FrameLayout>

MainActivity 主要代码片段:

//控件初始化让我贴出来就过分了啊。。。。。
indicator.setSize(imageViews.size() - 2);//头尾增加为了循环  但实际数量不要加
        viewPager.setCurrentItem(1);//设置当前位置
        viewPager.addOnPageChangeListener(indicator.getOnPageChangeListener());
        viewPager.addOnPageChangeListener(new LoopOnPageChangeListener(viewPager, imageViews.size()));

PagerAdapter 重要代码:

    // index  0 1 2 3 4 5
    // view   3 0 1 2 3 0
    // 如果debug你会发现PagerAdapter加载视图的顺序   例如首次显示view 0
    // instantiateItem 加载顺序为  view0 view3 view1
    // 手势左滑会触发  destroyItem view3  instantiateItem view2    以此类推
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = views.get(position);
        ViewGroup viewGroup = (ViewGroup) view.getParent();
        if (viewGroup != null) {//由于无限循环采用首位添加冗余的方式
            // 例如本例一共4个view,但是列表里有6个。当滑动index5完全显示时会控制viewPager跳到index1
            // 如果此处不判断view.getParent()的话,会发生java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
            // 因为list里index5和index1的对象是同一个因此不能够重复addview();
            viewGroup.removeView(view);
        }
        container.addView(view);
        return view;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //在instantiateItem里面处理
    }

OnPageChangeListener 主要代码:

@Override
    public void onPageSelected(int position) {
        targetPosition = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        // 不在onPageSelected 里处理
        // 是因为onPageSelected回调时界面可能还没有停止滑动
        // 因此会产生闪烁
        if (state == ViewPager.SCROLL_STATE_IDLE && targetPosition != currentPosition) {
            int index = targetPosition;
            if (targetPosition == size - 1) {
                index = 1;
            } else if (targetPosition == 0) {
                index = size - 2;
            }
            viewPager.setCurrentItem(index, false);
            currentPosition = targetPosition;
        }
    }

上面这些全部都是为了给LoopIndicator做基础,以上的知识网上一大堆不懂的可自行百度Google 关键字:android viewpager 无限循环

下面开始主题:
要想让Indicator随滑动变大变小首先要有一个缩放的比例,在OnPageChangeListener里有三个方法(自己看源码),我要的缩放比例在void onPageScrolled(int position, float positionOffset, int positionOffsetPixels);里有回调;
具体讲讲三个参数,其中由滑动方向不同参数变化是不一样的(注意踩坑)
手势左滑:position 不变,当void onPageSelected(int position)回调时会+1 ;positionOffset 会逐渐增加(0-1);positionOffsetPixels会逐渐增加(屏幕的宽)
左滑结束:会回调一个 position+1 positionOffset=0 positionOffsetPixels=0 注意此处的处理
手势右滑:一上来就position -1 ;positionOffset 会逐渐减小(0-1);positionOffsetPixels会逐渐减小(屏幕的宽)

如果没看懂可以自己打log看一看;
知道里变化的规律代码就好写了,我用的是LayoutParams来改变ImageView的缩放(如果有性能更优的方案还请大神不吝赐教指点一二)

关键逻辑:

 @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            Log.i("ljf", "position:" + position + "---------positionoffset:" + positionOffset + "---------positionOffsetPixels:" + positionOffsetPixels);
            if (positionOffset == 0) {
                return;
            }
            if (currentPosition == position) {//判断手势方向
                forward(position, positionOffset);
            } else {
                backup(position, positionOffset);
            }
        }
    private void forward(int position, float offset) {
        ImageView currentImageView = getImageView(position - 1);
        ImageView nextImageView = getImageView(position);
        action(currentImageView, nextImageView, offset);
    }

    private void backup(int position, float offset) {
        ImageView nextImageView = getImageView(position - 1);
        ImageView currentImageView = getImageView(position);
        action(currentImageView, nextImageView, 1 - offset);
    }

    private void action(ImageView currentImageView, ImageView nextImageView, float offset) {
        LinearLayout.LayoutParams layoutParams1 = (LinearLayout.LayoutParams) currentImageView.getLayoutParams();
        layoutParams1.width = selectWidth - (int) (normalWidth * offset);
        layoutParams1.height = selectWidth - (int) (normalWidth * offset);
        currentImageView.setLayoutParams(layoutParams1);

        LinearLayout.LayoutParams layoutParams2 = (LinearLayout.LayoutParams) nextImageView.getLayoutParams();
        layoutParams2.width = normalWidth + (int) (normalWidth * offset);
        layoutParams2.height = normalWidth + (int) (normalWidth * offset);
        nextImageView.setLayoutParams(layoutParams2);
    }

这里是项目代码:https://github.com/s1991721/Android

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现 ViewPager 的循环滑动,可以通过以下步骤: 1. 继承 ViewPager 类,重写 `onTouchEvent` 方法,使其支持循环滑动。 ```java public class LoopViewPager extends ViewPager { public LoopViewPager(Context context) { super(context); } public LoopViewPager(Context context, AttributeSet attrs) { super(context, attrs); } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { stopAutoScroll(); } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { startAutoScroll(); } return super.onTouchEvent(event); } } ``` 2. 重写 `onMeasure` 方法,使其支持 wrap_content。 ```java @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = 0; for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int h = child.getMeasuredHeight(); if (h > height) { height = h; } } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } ``` 3. 重写 `setAdapter` 方法,使其支持循环滑动。 ```java @Override public void setAdapter(PagerAdapter adapter) { super.setAdapter(adapter); setCurrentItem(0); } @Override public void setCurrentItem(int item) { int realCount = getRealCount(); if (realCount == 0) { super.setCurrentItem(item); return; } int position = getRealPosition(item); super.setCurrentItem(position); } private int getRealCount() { PagerAdapter adapter = getAdapter(); if (adapter == null) { return 0; } return adapter.getCount(); } private int getRealPosition(int position) { int realCount = getRealCount(); if (realCount == 0) { return 0; } return position % realCount; } ``` 4. 在 `onPageSelected` 回调中处理循环滑动的逻辑。 ```java @Override public void onPageSelected(int position) { int realCount = getRealCount(); if (realCount == 0) { return; } int realPosition = getRealPosition(position); if (realPosition == 0) { setCurrentItem(realCount, false); } else if (realPosition == realCount - 1) { setCurrentItem(1, false); } } ``` 5. 在 `startAutoScroll` 和 `stopAutoScroll` 方法中处理自动滑动的逻辑。 ```java private void startAutoScroll() { stopAutoScroll(); mHandler.postDelayed(mAutoScrollTask, mInterval); } private void stopAutoScroll() { mHandler.removeCallbacks(mAutoScrollTask); } private Runnable mAutoScrollTask = new Runnable() { @Override public void run() { int currentItem = getCurrentItem(); setCurrentItem(currentItem + 1, true); mHandler.postDelayed(this, mInterval); } }; ``` 完整的实现代码如下: ```java public class LoopViewPager extends ViewPager { private static final int DEFAULT_INTERVAL = 3000; private Handler mHandler = new Handler(); private int mInterval = DEFAULT_INTERVAL; public LoopViewPager(Context context) { super(context); init(); } public LoopViewPager(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { setPageTransformer(true, new DefaultTransformer()); } @Override public boolean onTouchEvent(MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_DOWN) { stopAutoScroll(); } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { startAutoScroll(); } return super.onTouchEvent(event); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int height = 0; for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int h = child.getMeasuredHeight(); if (h > height) { height = h; } } heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY); super.onMeasure(widthMeasureSpec, heightMeasureSpec); } @Override public void setAdapter(PagerAdapter adapter) { super.setAdapter(adapter); setCurrentItem(0); } @Override public void setCurrentItem(int item) { int realCount = getRealCount(); if (realCount == 0) { super.setCurrentItem(item); return; } int position = getRealPosition(item); super.setCurrentItem(position); } @Override public void setCurrentItem(int item, boolean smoothScroll) { int realCount = getRealCount(); if (realCount == 0) { super.setCurrentItem(item, smoothScroll); return; } int position = getRealPosition(item); super.setCurrentItem(position, smoothScroll); } @Override public int getCurrentItem() { int realCount = getRealCount(); if (realCount == 0) { return super.getCurrentItem(); } int position = super.getCurrentItem(); return getRealPosition(position); } private int getRealCount() { PagerAdapter adapter = getAdapter(); if (adapter == null) { return 0; } return adapter.getCount(); } private int getRealPosition(int position) { int realCount = getRealCount(); if (realCount == 0) { return 0; } return position % realCount; } @Override public void onPageSelected(int position) { int realCount = getRealCount(); if (realCount == 0) { return; } int realPosition = getRealPosition(position); if (realPosition == 0) { setCurrentItem(realCount, false); } else if (realPosition == realCount - 1) { setCurrentItem(1, false); } } public void setInterval(int interval) { mInterval = interval; } public void startAutoScroll() { stopAutoScroll(); mHandler.postDelayed(mAutoScrollTask, mInterval); } public void stopAutoScroll() { mHandler.removeCallbacks(mAutoScrollTask); } private Runnable mAutoScrollTask = new Runnable() { @Override public void run() { int currentItem = getCurrentItem(); setCurrentItem(currentItem + 1, true); mHandler.postDelayed(this, mInterval); } }; private static class DefaultTransformer implements ViewPager.PageTransformer { @Override public void transformPage(View page, float position) { if (position < -1) { page.setAlpha(0); } else if (position <= 1) { float scaleFactor = Math.max(0.75f, 1 - Math.abs(position - 0.125f)); page.setScaleX(scaleFactor); page.setScaleY(scaleFactor); } else { page.setAlpha(0); } } } } ``` 使用方式: ```xml <com.example.LoopViewPager android:id="@+id/view_pager" android:layout_width="match_parent" android:layout_height="wrap_content" /> ``` ```java LoopViewPager viewPager = findViewById(R.id.view_pager); PagerAdapter adapter = new MyPagerAdapter(); viewPager.setAdapter(adapter); viewPager.setInterval(3000); viewPager.startAutoScroll(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值