RecyclerView 高度不能随着Item数量 自适应高度

在最近项目中遇到 ,在RecyclerView加载list数据时,高度无法自适应增长,看了很多博客,各种尝试,都没有解决这个问题,在某个博客中,讲到此解决方法,在此记录下。

即在RecyclerView 布局时用 RelativeLayout 包裹着,即:

<RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/white"
                    android:orientation="vertical"
                    >
                <android.support.v7.widget.RecyclerView
                    android:id="@+id/id_rv_orders"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent" />

                </RelativeLayout>

 就可以自适应item数量高度

转载于:https://www.cnblogs.com/zty-Love/p/10124150.html

要让 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,请将它们的高度相加。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值