【问题标题】:How to show fixed count of items in Recyclerview?如何在 Recyclerview 中显示固定数量的项目?
【发布时间】:2017-08-30 12:29:46
【问题描述】:

我的任务是在屏幕上显示固定数量的项目。 这并不意味着我有固定大小的列表,这意味着滚动时应该只有 5 个项目可见。

如何实现? 我没有找到任何有用的信息。

【问题讨论】:

    标签: android android-recyclerview


    【解决方案1】:

    我也遇到了类似的问题。我几乎完美地解决了它。我选择扩展LinearLayoutManager

    public class MaxCountLayoutManager extends LinearLayoutManager {
    
        private int maxCount = -1;
    
        public MaxCountLayoutManager(Context context) {
            super(context);
        }
    
        public MaxCountLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }
    
        public MaxCountLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        public void setMaxCount(int maxCount) {
            this.maxCount = maxCount;
        }
    
        @Override
        public void setMeasuredDimension(int widthSize, int heightSize) {
            int maxHeight = getMaxHeight();
            if (maxHeight > 0 && maxHeight < heightSize) {
                super.setMeasuredDimension(widthSize, maxHeight);
            }
            else {
                super.setMeasuredDimension(widthSize, heightSize);
            }
        }
    
        private int getMaxHeight() {
            if (getChildCount() == 0 || maxCount <= 0) {
                return 0;
            }
    
            View child = getChildAt(0);
            int height = child.getHeight();
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            height += lp.topMargin + lp.bottomMargin;
            return height*maxCount+getPaddingBottom()+getPaddingTop();
        }
    }
    

    使用方法:

    # in kotlin
    rcyclerView.layoutManager = MaxCountLayoutManager(context).apply { setMaxCount(5) }
    

    但是每个item的高度需要相同,因为我只考虑了第一个item的高度和边距。

    【讨论】:

    • child.layoutParams.height 返回 -2 (WRAP_CONTENT) 但 child.height 返回正确的像素值
    • @YTerle 是的!你说的对。我写的代码只是一个参考思路。你可以用自己的方式实现它
    【解决方案2】:

    如果我正确地回答了您的问题,那么每当用户停止滚动时,您就会尝试在屏幕上显示固定数量的列表项。

    这可以通过计算屏幕高度/宽度,然后相应地设置列表项布局尺寸(高度/宽度)来完成。

    view.getLayoutParams().width = getScreenWidth() / VIEWS_COUNT_TO_DISPLAY;
    

    现在,根据您想要水平列表还是垂直列表,更改列表项布局的宽度或高度值。

    检查这些链接

    RecyclerView number of visible items

    How to show exact number of items in RecyclerView?

    【讨论】:

      【解决方案3】:

      最简单的解决方案是让onBindViewHolder() 动态设置其视图高度/宽度。对于垂直列表:

      float containerHeight = mRecyclerView.getHeight();
      holder.itemView.setMinimumHeight(Math.round(containerHeight/5));
      

      【讨论】:

        猜你喜欢
        • 2016-05-11
        • 2021-08-22
        • 1970-01-01
        • 1970-01-01
        • 2015-07-25
        • 2020-06-04
        • 1970-01-01
        • 1970-01-01
        • 2019-09-09
        相关资源
        最近更新 更多