Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

android - How to show fixed count of items in Recyclerview?

I have a task to show fixed count of items on the screen. It doens't mean that I have fixed size of list, it means that only 5 items should be visible when scrolling.

How it can be done? I didn't find any useful information about it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I also encountered a similar problem. I have solved it almost perfectly. I chose to extend 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();
    }
}

How to use:

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

But the height of each item needs to be the same, because I only considered the height and margin of the first item.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...