获取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 ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        bottomListLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);

                        int bottomHeight = bottomListLayout.getHeight();
                        LogUtils.e("bottomHeight: " + bottomHeight);

                        int bottomMeasuredHeight = bottomListLayout.getMeasuredHeight();
                        LogUtils.e("bottomMeasuredHeight: " + bottomMeasuredHeight);

                        int rvHeight = rvList.getHeight();
                        LogUtils.e("rvHeight: " + rvHeight);

                        int rvMeasuredHeight = rvList.getMeasuredHeight();
                        LogUtils.e("rvMeasuredHeight: " + rvMeasuredHeight);

                        int count = rvList.getChildCount();
                        LogUtils.e("count: " + count);

                        sheetBehavior2.setPeekHeight(bottomMeasuredHeight / count);
                    }
                });

        // 设置为false 下拉无法隐藏,设置为true,下拉可以隐藏
        sheetBehavior2.setHideable(false);

输出结果:

bottomHeight: 2312
bottomMeasuredHeight: 2312
rvHeight: 2248
rvMeasuredHeight: 2248
count: 5
发布了632 篇原创文章 · 获赞 758 · 访问量 51万+

猜你喜欢

转载自blog.csdn.net/songzi1228/article/details/103696512