RecyclerView 更改对齐方式

老规矩, 无图言D, 直接上图

代码

package com.pb.test.bilibili.home

import android.content.Context
import android.graphics.PointF
import android.util.DisplayMetrics
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView
import kotlin.math.ceil
import kotlin.math.sqrt

/**
 *
 * @author : YingYing Zhang
 * @e-mail : 540108843@qq.com
 * @time   : 2023-02-25
 * @desc   :
 *
 */
class SnapLayoutManager(
    val context: Context, orientation: Int = RecyclerView.HORIZONTAL, reverseLayout: Boolean = false,
    val isInAbTest: Boolean = false
) : LinearLayoutManager(context, orientation, reverseLayout) {

    override fun smoothScrollToPosition(
        recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int
    ) {
        val smoothScroller = object : LinearSmoothScroller(context) {
            override fun getVerticalSnapPreference() = SNAP_TO_START

            override fun getHorizontalSnapPreference() = SNAP_TO_START

        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }
}

小小总结

对, 没错, 两行代码就实现了, 只需要重写 getVerticalSnapPreference 和 getHorizontalSnapPreference, 指定返回值为 SNAP_TO_START, recyclerView 每次滑动后, 就会对齐到 item 左边了, 还有其他返回值, 可以自行研究.

当然如果想要做出来上"图"中的效果, 需要好好计算 recyclerView 一下, 当然需要根据需求细节来实现对应的效果, 由于"图"中的代码写的不好, 就不贴了, 主要是之前不知道 layoutManager 有这个方法 SNAP_TO_START, 一直没有找到实现方案, 踩了很多坑...

当然自定义 SnapHelper 也可以实现类似效果, 不过要根据具体的需求来讨论了, 就比如我这里是需要实现翻页效果, 但翻页后, 如果没有达到翻页临界值, 需要返回之前页, 但这时发现找不到对应的 item 了(被回收了...), 我哭死, 代码都快写完了, 才发现实现不了...

有需要的小伙伴直接拿走, 如有问题, 请留言~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吃饱很舒服

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值