让RecyclerView自适应item数量高度,禁止单独滑动

最近在用recyclerview 来显示数据,但问题是在布局中,如果有多个控件在一起的话,recyclerview子布局数量一多就会自己滑动,让人的体验不是很好,所以我解决了这个问题,让recyclerview有多少item的时候显示多少,随着屏幕滑动,把自己的滑动给禁用了。

下面是布局文件:

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <androidx.recyclerview.widget.RecyclerView
                android:overScrollMode="never"
                android:visibility="invisible"
                android:id="@+id/recyclerContent"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

        </RelativeLayout>
</ScrollView>

这里的recyclerview 用relativelayout 套着,作用是先recyclerview的数据全部显示出来,如果不用的话,rc只能显示一部分的item,然后再外层是scrollview ,这里的作用是让滑动更加流畅,如果不加srollview的话,去滑动rc 就只能滑动一下,滚一下的效果。

下面还要把 rc 的水平或者垂直方向的滑动禁用了,重写布局管理器,这里我用的是LinearLayoutManager,下面贴代码

import android.content.Context
import androidx.recyclerview.widget.LinearLayoutManager

class MyLayoutManager(val context: Context):LinearLayoutManager(context) {
    override fun canScrollVertically(): Boolean {
        return false
    }
}

canScrollVertically 方法是垂直滑动,返回false就行了。

 

最后,设置完效果也就出来!!!

又添了一个坑,我想应该有更好的解决方法吧。

要让 RecyclerView高度随着子项自适应,可以采用以下两种方法: 方法一:使用 WrapContentLinearLayoutManager WrapContentLinearLayoutManager 是 RecyclerView 的一个布局管理器,可以让 RecyclerView高度随着子项自适应。 首先,需要在项目的 build.gradle 中添加以下依赖: ``` implementation 'com.github.azhao1981:WrapContentLinearLayoutManager:v1.0.1' ``` 接着,在代码中设置 RecyclerView 的布局管理器为 WrapContentLinearLayoutManager,如下: ```java WrapContentLinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(this); recyclerView.setLayoutManager(layoutManager); ``` 方法二:手动计算高度 另一种方法是手动计算 RecyclerView高度,具体步骤如下: 1. 在 RecyclerView 的 Adapter 中,添加一个方法用于计算 RecyclerView高度: ```java public int getItemHeight() { int height = 0; for (int i = 0; i < getItemCount(); i++) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_layout, null); view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); height += view.getMeasuredHeight(); } return height; } ``` 2. 在 Activity 或 Fragment 中获取 RecyclerView高度,并设置给 RecyclerView: ```java int height = mAdapter.getItemHeight(); ViewGroup.LayoutParams layoutParams = recyclerView.getLayoutParams(); layoutParams.height = height; recyclerView.setLayoutParams(layoutParams); ``` 其中,getItemHeight() 方法中的 R.layout.item_layout 是 RecyclerView 的子项布局文件。如果 RecyclerView 的子项布局文件中包含了多个子 View,请将它们的高度相加。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

雫和春的故事

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

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

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

打赏作者

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

抵扣说明:

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

余额充值