如何在 Recyclerview 中显示固定数量的项目? [英] How to show fixed count of items in Recyclerview?
本文介绍了如何在 Recyclerview 中显示固定数量的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一项任务要在屏幕上显示固定数量的项目.这并不意味着我有固定大小的列表,这意味着滚动时应该只看到 5 个项目.
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.
推荐答案
我也遇到了类似的问题.我几乎完美地解决了它.我选择扩展 LinearLayoutManager
.
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();
}
}
使用方法:
# in kotlin
rcyclerView.layoutManager = MaxCountLayoutManager(context).apply { setMaxCount(5) }
但是每个item的高度需要一致,因为我只考虑了第一个item的高度和边距.
But the height of each item needs to be the same, because I only considered the height and margin of the first item.
这篇关于如何在 Recyclerview 中显示固定数量的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文