稍微巧妙的双模块联动-ViewPager

语言: CN / TW / HK

小知识,大挑战!本文正在参与「程序员必备小知识」创作活动

本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金。

上个月我们项目开启了新的版本,有一个双模块联动的效果印象很深,这次就记录下来供大家参考一下

预计效果

联动1.gif

这个部分一开始是上面或者下面滑动到上一个或下一个时 另一个才会进行移动,苹果同学那边好像很简单的就搞定了,我们这边就需要特别改造一下Viewpager.

第一步就是先实现上面的画廊效果,这个倒是不难,下面是代码

activity.xml

```

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewpager1"
    android:layout_width="200dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_height="200dp"
    android:layout_marginTop="20dp"
    android:clipChildren="false"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.viewpager.widget.ViewPager
    android:layout_marginTop="30dp"
    android:id="@+id/viewpager2"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintTop_toBottomOf="@id/viewpager1" />

``` activity

``` public class ViewpagerActivity extends AppCompatActivity {

private ViewPager mViewpager1;
private ViewPager mViewpager2;

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

private void initView() {
    mViewpager1 = findViewById(R.id.viewpager1);
    mViewpager2 = findViewById(R.id.viewpager2);
    zoomOutPageTransformer = new ZoomOutPageTransformer();
    mViewpager1.setPageMargin(ImageUtil.dp2px(this, 20));
    mViewpager1.setPageTransformer(true, zoomOutPageTransformer);
    mViewpager1.setAdapter(new TopViewPgaerAdapter(this));
    mViewpager2.setAdapter(new BottomViewPagerAdapter(this));
    //缓存一下,不然会出现位置错乱
    mViewpager1.setOffscreenPageLimit(5);
    mViewpager2.setOffscreenPageLimit(5);
}

} **ZoomOutPageTransformer** //画廊 public class ZoomOutPageTransformer implements ViewPager.PageTransformer{ //自由控制缩放比例 private static final float MAX_SCALE = 1f; private static final float MIN_SCALE = 0.8f;//0.85f

@Override
public void transformPage(View page, float position) {

    if (position <= 1) {
        float scaleFactor = MIN_SCALE + (1 - Math.abs(position)) * (MAX_SCALE - MIN_SCALE);
        page.setScaleX(scaleFactor);
        if (position > 0) {
            page.setTranslationX(-scaleFactor * 2);
        } else if (position < 0) {
            page.setTranslationX(scaleFactor * 2);
        }
        page.setScaleY(scaleFactor);
    } else {
        page.setScaleX(MIN_SCALE);
        page.setScaleY(MIN_SCALE);
    }
}

} ```

这个用的是网络上某位兄弟的代码,这里我也找不到原作者了,复制百度一下一堆相同的,感谢那位兄弟提供的轮子代码.

TopViewPgaerAdapter ``` class TopViewPgaerAdapter(var context: Context) : PagerAdapter() { override fun getCount(): Int { return 5 }

override fun isViewFromObject(view: View, `object`: Any): Boolean {
    return view == `object`
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
}

override fun instantiateItem(container: ViewGroup, position: Int): Any {
    val inflate = LayoutInflater.from(context).inflate(R.layout.item_top, container, false)
    container.addView(inflate)
    return inflate
}

} **item_top**

<androidx.constraintlayout.utils.widget.ImageFilterButton
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@color/teal_200"/>

```

BottomViewPagerAdapter ``` class BottomViewPagerAdapter(var context: Context) : PagerAdapter() { override fun getCount(): Int { return 5 }

override fun instantiateItem(container: ViewGroup, position: Int): Any {
    val inflate = LayoutInflater.from(context).inflate(R.layout.item_parent, container, false)
    container.addView(inflate)

    return inflate
}

override fun isViewFromObject(view: View, `object`: Any): Boolean {
    return view === `object`
}

override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
}

} **item_parent**

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="撒打发建行卡沙发开讲啦啥大富科技阿斯顿

撒打发建行卡沙发开讲啦啥大富科技阿斯顿\n 撒打发建行卡沙发开讲啦啥大富科技阿斯顿\n 撒打发建行卡沙发开讲啦啥大富科技阿斯顿\n" android:textSize="20dp" android:textStyle="italic" /> ```

效果

联动2.gif

效果还不错,雏形已经准备完毕,开始完善细节

首先在initView加这么几行代码

``` BaseLinkPageChangeListener baseLinkPageChangeListener = new BaseLinkPageChangeListener(mViewpager1, mViewpager2, this, true); mViewpager1.addOnPageChangeListener( baseLinkPageChangeListener);

BaseLinkPageChangeListener baseLinkPageChangeListener1 = new BaseLinkPageChangeListener(mViewpager2, mViewpager1, this, false); baseLinkPageChangeListener1.setZoomOutPageTransformer(zoomOutPageTransformer); mViewpager2.addOnPageChangeListener(baseLinkPageChangeListener1); **BaseLinkPageChangeListener** public class BaseLinkPageChangeListener implements ViewPager.OnPageChangeListener {

private final ViewPager linkViewPager;
private final ViewPager selfViewPager;
private final Activity activity;
private ZoomOutPageTransformer zoomOutPageTransformer;
private final boolean isTop;

private int marginX = 0;

public BaseLinkPageChangeListener(ViewPager selfViewPager, ViewPager linkViewPager, Activity activity, boolean isTop) {
    this.linkViewPager = linkViewPager;
    this.selfViewPager = selfViewPager;
    this.activity = activity;
    this.isTop = isTop;
}

public void setZoomOutPageTransformer(ZoomOutPageTransformer zoomOutPageTransformer) {
    this.zoomOutPageTransformer = zoomOutPageTransformer;
}

@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    //计算移动值
    marginX = ((selfViewPager.getWidth() + selfViewPager.getPageMargin()) * position
            + positionOffsetPixels) * (linkViewPager.getWidth() + linkViewPager.getPageMargin()) / (
            selfViewPager.getWidth()
                    + selfViewPager.getPageMargin());

    if (linkViewPager.getScrollX() != marginX) {
        linkViewPager.scrollTo(marginX, 0);
    }

    //如果是底部viewpager,那么在滑动的时候也要响应的将动画给带动起来
    if (!isTop) {
        if (zoomOutPageTransformer != null) {
            final int scrollX = marginX;
            final int childCount = linkViewPager.getChildCount();
            for (int i = 0; i < childCount; i++) {
                final View child = linkViewPager.getChildAt(i);
                final ViewPager.LayoutParams lp = (ViewPager.LayoutParams) child.getLayoutParams();

                if (lp.isDecor) continue;
                final float transformPos = (float) (child.getLeft() - scrollX) / ImageUtil.dp2px(activity,200);
                //重要!!!
                zoomOutPageTransformer.transformPage(child, transformPos);
            }
        }
    }
}

@Override
public void onPageSelected(int position) {

}

@Override
public void onPageScrollStateChanged(int state) {

// if (state == ViewPager.SCROLL_STATE_IDLE) { // linkViewPager.setCurrentItem(position); // } } } ```

这个是最为重要的一个类了,主要涉及到滑动处理,self就是当前viewpager,link就是另一个viewpager

效果

联动3.gif

我在实际项目的使用中是拿到数据后在setadapter加setOffscreenPageLimit,你也可以拿到数据后notifyDataSetChanged然后setOffscreenPageLimit设置缓存,缓存是必须的,不然会动画,数据错乱

``` Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(@NonNull Message msg) { topViewPgaerAdapter.setPos(5); bottomViewPagerAdapter.setPos(5);

    topViewPgaerAdapter.notifyDataSetChanged();
    bottomViewPagerAdapter.notifyDataSetChanged();

    mViewpager1.setOffscreenPageLimit(5);
    mViewpager2.setOffscreenPageLimit(5);
    return true;
}

}); ```

简单用handler实现了一个伪环境,setPos就是getcount需要的值,这样也是可以的,其实不必要使用PagerAdapter也可以使用FragmentPagerAdapter,用Fragment实现更复杂丰富的页面,我这里只是提供一个思路

好了,摸鱼时间结束,开始优化项目啦!!!