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

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.png0605c411152c3938fc684b1a11aa2d2c.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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/501050.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

JAVA进阶教学之(Date日期的处理)

两个类&#xff1a; Date类&#xff1a;获取系统当前日期&#xff0c;属于java.util.Date包内 SimpleDateFormat类&#xff1a;将当前日期进行格式化处理&#xff0c;yyy-MM-dd HH:mm:ss SSS 代码演示&#xff1a; Date转String package com.lbj.javase.date;import java.tex…

检测到磁盘可能为uefi引导_在本地硬盘安装WinPE系统,实现UEFI引导,摆脱U盘

之前装系统一直用U盘装PE后再装系统&#xff0c;这次直接想把PE系统直接装在本地某个分区中&#xff0c;普通的PE制作工具只能直接装在一个硬盘里没法装在某个分区&#xff0c;百度发现没有一篇类似的文章&#xff0c;只能自己想办法了。目前的PE都支持UEFI引导了&#xff0c;所…

JAVA进阶教学之(数字格式化和高精度数字)

数字的格式化方便我们对于统计数字的时候便于区分 代码演示&#xff1a; new DecimalFormat("###,###.##"); package com.lbj.javase.number;import java.text.DecimalFormat;public class DecimalFormatTest01 {public static void main(String[] args) {//java.t…

mouted vue 操作dom_vue中关于dom的操作

mounted个人理解为DOM结构准备就绪了&#xff0c;可以开始加载vue数据了&#xff0c;挂载点&#xff0c;配合使用mounted:function(){this.$nextTick(function(){ //this.$nextTick是在下次DOM更新循环结束时调用延迟回调函数。异步函数this.loadData();          //…

delphi gui编辑工具源码_Python 快速构建一个简单的 GUI 应用

点击上方“AirPython”&#xff0c;选择“加为星标”第一时间关注 Python 技术干货&#xff01;1. 介绍Python GUI 常用的 3 种框架是&#xff1a;Tkinter、wxpython、PyQt5PyQt5 基于 Qt&#xff0c;是 Python 和 Qt 的结合体&#xff0c;可以用 Python 语言编写跨平台的 GUI …

Python入门级教学之(Python中的输出函数)

print()函数 括号内容可以是数字、字符串、含有运算符的表达式 输出的目的地是显示器、文件 输出的形式是换行、不换行 代码演示&#xff1a; # 项目负责人: LBJ # 开发日期&#xff1a;2021/3/16 20:36# 输出数字、字符串、运算表达式 print(123) print("123") pri…

submlime text写java_在Sublime Text 3中配置编译和运行Java程序

1.设置java的PATH环境变量2.创建批处理或Shell脚本文件要想编译运行Java程序&#xff0c;需要创建一个批处理或者Shell脚本Windows&#xff1a;runJava.bat:echo offcd %~dp1echo Compiling %~nx1......if exist %~n1.class (del %~n1.class)javac %~nx1if exist %~n1.class (e…

processing创意图形代码_2020年外贸B2C店铺的黑色星期五创意营销想法(下)

10.外贸B2C店铺黑色星期五创意营销理念——创建促销内容日历随着黑色星期五的临近&#xff0c;您将希望巩固自己的整体策略。伟大的第一步是创建一个内容日历&#xff0c;其中要共享什么资产和内容以及何时共享。计划提前一个月计划&#xff0c;并在黑色星期五的一周开始促销活…

Python入门教学之(转义字符与原字符)

转义字符&#xff1a; \想要转义功能的首小写字母 例如&#xff1a; 换行 \n print("hello\nworld") 占位符 \t&#xff08;占用4个字符&#xff09; print("hello\tworld") # 由于前面字符占位是5个字符位&#xff0c;后面占位符就占3个字符位 print(…

vi编辑器 末尾添加_vim编辑器

1. 关于Vimvim是我最喜欢的编辑器&#xff0c;也是linux下第二强大的编辑器。 虽然emacs是公认的世界第一&#xff0c;我认为使用emacs并没有使用vi进行编辑来得高效。 如果是初学vi&#xff0c;运行一下vimtutor是个聪明的决定。 (如果你的系统环境不是中文&#xff0c;而你想…

python 识别图形验证码_Python验证码识别

大致介绍在python爬虫爬取某些网站的验证码的时候可能会遇到验证码识别的问题&#xff0c;现在的验证码大多分为四类&#xff1a;1、计算验证码2、滑块验证码3、识图验证码4、语音验证码这篇博客主要写的就是识图验证码&#xff0c;识别的是简单的验证码&#xff0c;要想让识别…

Python入门教学之(标识符和保留字)

1、查看Python的所有关键字 import keyword print(keyword.kwlist) 结果&#xff1a; [False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not,…

sequelize 外键关联_mysql – Sequelize.js外键

在我有同样的问题之前,当我了解设置功能的时候,解决了.开门见山&#xff01;假设我们有两个对象&#xff1a;人与父亲var Person sequelize.define(Person, {name: Sequelize.STRING});var Father sequelize.define(Father, {age: Sequelize.STRING,//The magic start herepe…

pep8 python 编码规范_实用的python编码规范

编码规范在程序开发中是一项很重要要求&#xff0c;良好的编码规范对程序的可读性、代码的可维护性都有很大的提高&#xff0c;从而提高开发效率。下面总结了python中一些实用的开发规范&#xff0c;供大家借鉴和参考。1.每行不超过80个字符每行代码太长既不美观也影响可读性&a…

JAVA进阶教学之(产生随机数)

import java.util.Random;代码演示&#xff1a; package com.lbj.javase.random;import java.util.Random;public class RandomTest01 {public static void main(String[] args) {//创建随机数对象Random randomnew Random();int num1random.nextInt();System.out.println(num…

python中char的用法_如何从C++返回char **并使用cType在Python中填充它?

我一直试图从C返回一个字符串数组到Python&#xff0c;如下&#xff1a;// c codeextern "C" char** queryTree(char* treename, float rad, int kn, char*name, char *hash){//.... bunch of other manipulation using parameters...int nbr 3; // number of strin…

python txt转json_实战篇 | 用Python来找你喜欢的妹子(二)

用Python做有趣的事情最近整理一个爬虫系列方面的文章&#xff0c;不管大家的基础如何&#xff0c;我从头开始整一个爬虫系列方面的文章&#xff0c;让大家循序渐进的学习爬虫&#xff0c;小白也没有学习障碍.爬虫篇&#xff1a;使用Python动态爬取某大V微博&#xff0c;再用词…

yoga710怎么进入bios_【解读YOGA——BIOS篇】找回消失掉的BIOS,YOGA BIOS详解!

本帖最后由 Harrisheagle 于 2012-11-1 09:51 编辑相信每位机油在拿到新本本的时候&#xff0c;都有开机进入BIOS逛一逛的习惯。这个我也不例外&#xff0c;拿到YOGA的那一刻&#xff0c;我就迫不及待地想看看这款如此特别的YOGA&#xff0c;究竟它的BIOS会给我带来什么惊喜呢&…

JAVA进阶教学之(Enum枚举类)

首先&#xff0c;我们为什么要学习Enum枚举类 我们引入一段代码&#xff1a; package com.lbj.javase.enumTest;public class EnumTest01 {public static void main(String[] args) {int retValuedivide(10,2);System.out.println(retValue);int retValue2divide(10,0);Syste…

python中的get函数_python之函数用法get()

# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之函数用法get() #http://www.runoob.com/python/att-dictionary-get.html #dict.get(key, defaultNone) #说明&#xff1a;返回指定键的值&#xff0c;如果值不在字典中返回默认值. #key:要查找的键 #default:如果指定键…