获取RecyclerView的item的高度

1、在onCreate()方法中获取

        // 没有意义,获取到的结果都为零
        int bottomHeight = bottomListLayout.getHeight();
        LogUtils.e("bottomHeight: " + bottomHeight);
        int bottomMeasuredHeight = bottomListLayout.getMeasuredHeight();
        LogUtils.e("bottomMeasuredHeight: " + bottomMeasuredHeight);
        int rvHeight = rvList.getHeight();
        LogUtils.e("rvHeight: " + rvHeight);

通过以上方式是获取不到的,获取的结果为0。

2、解决方案

获取 ViewTreeObserver 并注册 OnGlobalLayoutListener(当全局布局状态改变或者视图树中视图的可见性发生变化时会进行调用),在这个监听中我们就可以获取 RecyclerView 的高度了

bottomListLayout = findViewById(R.id.bottomListLayout);
sheetBehavior2 = BottomSheetBehavior.from(bottomListLayout);

ViewTreeObserver vto = bottomListLayout.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(
                new
  • 6
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
要让 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,请将它们的高度相加。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值