viewpager 自定义翻页效果_Android RecyclerView自定义LayoutManager

本文介绍了如何在Android中自定义RecyclerView的LayoutManager以实现独特的翻页效果。通过覆盖onLayoutChildren()方法布局Item,并在滚动过程中添加效果。同时,文章详细讲解了如何判断滚动到顶部和底部,以防止过度滚动。
摘要由CSDN通过智能技术生成

8f7644ca7c2d43f3fdf25109c815e2c3.gif

在第一篇中已经讲过,LayoutManager主要用于布局其中的Item,在LayoutManager中能够对每个Item的大小,位置进行更改,将它放在我们想要的位置,在很多优秀的效果中,都是通过自定义LayoutManager来实现的,比如:

201b259671d9168294169efc6ec9e010.png

Github: https://github.com/dongjunkun/RecyclerViewAccentFirst

可以看到效果非常棒,通过这一节的学习,大家也就理解了自定义LayoutManager的方法,然后再理解这些控件的代码就不再难了。

在这节中,我们先自己制作一个LinearLayoutManager,来看下如何自定义LayoutManager,下节中,我们会通过自定义LayoutManager来制作第一个滚轮翻页的效果。

自定义CustomLayoutManager

先生成一个类CustomLayoutManager,派生自LayoutManager:

public class CustomLayoutManager extends LayoutManager {
    @Override
    public LayoutParams generateDefaultLayoutParams() {
        return null;
    }
}

当我们派生自LayoutManager时,会强制让我们生成一个方法generateDefaultLayoutParams。这个方法就是RecyclerView Item的布局参数,换种说法,就是RecyclerView 子 item 的 LayoutParameters,若是想修改子Item的布局参数(比如:宽/高/margin/padding等等),那么可以在该方法内进行设置。一般来说,没什么特殊需求的话,则可以直接让子item自己决定自己的宽高即可(wrap_content)。

public class CustomLayoutManager extends LayoutManager {
    @Override
    public LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT,
                RecyclerView.LayoutParams.WRAP_CONTENT);
    }
}

如果这时候,我们把上节demo中LinearLayoutManager替换下:

public class LinearActivity extends AppCompatActivity {
    private ArrayList mDatas = new ArrayList<>();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linear);
        …………
        RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.linear_recycler_view);
        mRecyclerView.setLayoutManager(new CustomLayoutManager());
        RecyclerAdapter adapter = new RecyclerAdapter(this, mDatas);
        mRecyclerView.setAdapter(adapter);
    }
    …………
}

运行一下,发现页面完全空白:

86459ea321b86ccaf3e34aedaadf92a1.png

我们说过所有的Item的布局都是在LayoutManager中处理的,很明显,我们目前在CustomLayoutManager中并没有布局任何的Item。当然没有Item出现了。

onLayoutChildren()

LayoutManager中,所有Item的布局都是在onLayoutChildren()函数中处理的,所以我们在CustomLayoutItem中添加onLayoutChildren()函数:

@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    //定义竖直方向的偏移量
    int offsetY = 0;
    for (int i = 0; i         View view = recycler.getViewForPosition(i);
        addView(view);
        measureChildWithMargins(view, 0, 0);
        int width = getDecoratedMeasuredWidth(view);
        int height = getDecoratedMeasuredHeight(view);
        layoutDecorated(view, 0, offsetY, width, offsetY + height);
        offsetY += height;
    }
}

在这个函数中,我主要做了两个事:第一:把所有的item所对应的view加进来:

for (int i = 0; i     View view = recycler.getViewForPosition(i);
    addView(view);
    …………
}

第二:把所有的Item摆放在它应在的位置:

public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    //定义竖直方向的偏移量
    int offsetY = 0;
    for (int i = 0; i         …………
        measureChildWithMargins(view, 0, 0);
        int width = getDecoratedMeasuredWidth(view);
        int height = getDecoratedMeasuredHeight(view);
        layoutDecorated(view, 0, offsetY, width, offsetY + height);
        offsetY += height;
    }
}

measureChildWithMargins(view, 0, 0);函数测量这个View,并且通过getDecoratedMeasuredWidth(view)得到测量出来的宽度,需要注意的是通过getDecoratedMeasuredWidth(view)得到的是item+decoration的总宽度。如果你只想得到view的测量宽度,通过View.getMeasuredWidth()就可以得到了。

然后通过layoutDecorated()函数将每个item摆放在对应的位置,每个Item的左右位置都是相同的,从左侧x=0开始摆放,只是y的点需要计算。所以这里有一个变量offsetY,用以累加当前Item之前所有item的高度。从而计算出当前item的位置。这个部分难度不大,就不再细讲了。

在此之后,我们再运行程序,会发现,现在item显示出来了:

806e9e665fe9bc066153c9795b28da9f.png

添加滚动效果

但是,现在还不能滑动,如果我们要给它添加上滑动,需要修改两个地方:

@Override
public boolean canScrollVertically() {
    return true;
}

@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
    // 平移容器内的item
    offsetChildrenVertical(-dy);
    return dy;
}

我们通过在canScrollVertically()return true;使LayoutManager具有垂直滚动的功能。然后scrollVerticallyBy中接收每次滚动的距离dy。如果你想使LayoutManager具有横向滚动的功能,可以通过在canScrollHorizontally()中`return true;``

这里需要注意的是,在scrollVerticallyBy中,dy表示手指在屏幕上每次滑动的位移。

  • 当手指由下往上滑时,dy>0
  • 当手指由上往下滑时,dy<0

当手指向上滑动时,我们需要让所有子Item向上移动,向上移动明显是需要减去dy的。所以,大家经过测试也可以发现,让容器内的item移动-dy距离,才符合生活习惯。在LayoutManager中,我们可以通过public void offsetChildrenVertical(int dy)函数来移动RecycerView中的所有item。

现在我们再运行一下:

c80782f4f5ac7fee10a540bd650b48ab.png

6bf0bd459119634ea9eb767cd8bb45a4.png

这里虽然实现了滚动,但是Item到顶之后,仍然可以滚动,这明显是不对的,我们需要在滚动时添加判断,如果到顶了或者到底了就不让它滚动了。

判断到顶

判断到顶相对比较容易,我们只需要把所有的dy相加,如果小于0,就表示已经到顶了。就不让它再移动就行,代码如下:

private int mSumDy = 0;
@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
    int travel = dy;
    //如果滑动到最顶部
    if (mSumDy + dy 0) {
        travel = -mSumDy;
    }
    mSumDy += travel;
    // 平移容器内的item
    offsetChildrenVertical(-travel);
    return dy;
}

在这段代码中,通过变量mSumDy 保存所有移动过的dy,如果当前移动的距离<0,那么就不再累加dy,直接让它移动到y=0的位置,因为之前已经移动的距离是mSumdy; 所以计算方法为:

travel+mSumdy = 0;
=> travel = -mSumdy

所以要将它移到y=0的位置,需要移动的距离为-mSumdy,效果如下图所示:

0d4ac9e81fc5c6ec7a35f3e958b8a390.png

从效果图中可以看到,现在在到顶时,就不会再移动了。下面再来看看到底的问题。

判断到底

判断到底的方法,其实就是我们需要知道所有item的总高度,用总高度减去最后一屏的高度,就是到底的时的偏移值,如果大于这个偏移值就说明超过底部了。

所以,我们首先需要得到所有item的总高度,我们知道在onLayoutChildren中会测量所有的item并且对每一个item布局,所以我们只需要在onLayoutChildren中将所有item的高度相加就可以得到所有Item的总高度了。

private int mTotalHeight = 0;
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
    //定义竖直方向的偏移量
    int offsetY = 0;
    for (int i = 0; i         View view = recycler.getViewForPosition(i);
        addView(view);
        measureChildWithMargins(view, 0, 0);
        int width = getDecoratedMeasuredWidth(view);
        int height = getDecoratedMeasuredHeight(view);
        layoutDecorated(view, 0, offsetY, width, offsetY + height);
        offsetY += height;
    }
    //如果所有子View的高度和没有填满RecyclerView的高度,
    // 则将高度设置为RecyclerView的高度
    mTotalHeight = Math.max(offsetY, getVerticalSpace());
}
private int getVerticalSpace() {
    return getHeight() - getPaddingBottom() - getPaddingTop();
}

getVerticalSpace()函数可以得到RecyclerView用于显示Item的真实高度。而相比上面的onLayoutChildren,这里只添加了一句代码:mTotalHeight = Math.max(offsetY, getVerticalSpace());这里只所以取最offsetYgetVerticalSpace()的最大值是因为,offsetY是所有item的总高度,而当item填不满RecyclerView时,offsetY应该是比RecyclerView的真正高度小的,而此时的真正的高度应该是RecyclerView本身所设置的高度。

接下来就是在scrollVerticallyBy中判断到底并处理了:

public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
    int travel = dy;
    //如果滑动到最顶部
    if (mSumDy + dy 0) {
        travel = -mSumDy;
    } else if (mSumDy + dy > mTotalHeight - getVerticalSpace()) {
        travel = mTotalHeight - getVerticalSpace() - mSumDy;
    }

    mSumDy += travel;
    // 平移容器内的item
    offsetChildrenVertical(-travel);
    return dy;
}

mSumDy + dy > mTotalHeight - getVerticalSpace()中:mSumDy + dy表示当前的移动距离,mTotalHeight - getVerticalSpace()表示当滑动到底时滚动的总距离;

当滑动到底时,此次的移动距离要怎么算呢? 算法如下:

travel + mSumDy = mTotalHeight - getVerticalSpace();

即此将将要移动的距离加上之前的总移动距离,应该是到底的距离。=> travel = mTotalHeight - getVerticalSpace() - mSumDy;

现在再运行一下代码,可以看到,这时候的垂直滑动列表就完成了:

ad05334f1867326596bd40935f1b7658.png 0605c411152c3938fc684b1a11aa2d2c.png


从列表中可以看出,现在到顶和到底可以继续滑动的问题就都解决了。下面贴出完整的CustomLayoutManager代码,供大家参考:

package com.example.myrecyclerview;

import android.util.Log;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

public class CustomLayoutManager extends RecyclerView.LayoutManager {

    @Override
    public RecyclerView.LayoutParams generateDefaultLayoutParams() {
        return new RecyclerView.LayoutParams(RecyclerView.LayoutParams.WRAP_CONTENT,
                RecyclerView.LayoutParams.WRAP_CONTENT);
    }

    private int mTotalHeight = 0;

    public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
        //定义竖直方向的偏移量
        int offsetY = 0;
        for (int i = 0; i             View view = recycler.getViewForPosition(i);
            addView(view);
            measureChildWithMargins(view, 0, 0);
            int width = getDecoratedMeasuredWidth(view);
            int height = getDecoratedMeasuredHeight(view);
            layoutDecorated(view, 0, offsetY, width, offsetY + height);
            offsetY += height;
        }
        //如果所有子View的高度和没有填满RecyclerView的高度,
        // 则将高度设置为RecyclerView的高度
        mTotalHeight = Math.max(offsetY, getVerticalSpace());
    }

    private int getVerticalSpace() {
        return getHeight() - getPaddingBottom() - getPaddingTop();
    }


    @Override
    public boolean canScrollVertically() {
        return true;
    }

    private int mSumDy = 0;

    @Override
    public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
        int travel = dy;
        //如果滑动到最顶部
        if (mSumDy + dy 0) {
            travel = -mSumDy;
        } else if (mSumDy + dy > mTotalHeight - getVerticalSpace()) {
            travel = mTotalHeight - getVerticalSpace() - mSumDy;
        }
        mSumDy += travel;
        // 平移容器内的item
        offsetChildrenVertical(-travel);
        return dy;
    }
}

完!

---END---

推荐阅读:
Android | 自定义上拉抽屉+组合动画效果
重磅!!Gradle 6.6 发布,大幅提升性能!
Flutter(Flare) 最有趣用户交互动画没有之一
怒爬某破Hub站资源,只为撸这个鉴黄平台!
Flutter 10天高仿大厂App及小技巧积累总结
阿里巴巴官方最新Redis开发规范!
涉嫌侵害用户权益,这101款App被点名!

cda507450e6b5328aaab1b38abb6fd5e.png

更文不易,点个“在看”支持一下?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值