[英]How to show fixed count of items in Recyclerview?
我有一项任务是在屏幕上显示固定数量的项目。 这并不意味着我有固定大小的列表,这意味着滚动时应该只看到 5 个项目。
怎么做? 我没有找到任何关于它的有用信息。
我也遇到了类似的问题。 我几乎完美地解决了它。 我选择扩展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的高度和边距。
如果我正确地回答了您的问题,则每当用户停止滚动时,您都会尝试在屏幕上显示固定数量的列表项。
这可以通过计算屏幕高度/宽度然后相应地设置列表项布局尺寸(高度/宽度)来完成。
view.getLayoutParams().width = getScreenWidth() / VIEWS_COUNT_TO_DISPLAY;
现在,根据您想要水平列表还是垂直列表,更改列表项布局的宽度或高度值。
检查这些链接
最简单的解决方案是让onBindViewHolder()
动态设置其视图高度/宽度。 对于垂直列表:
float containerHeight = mRecyclerView.getHeight();
holder.itemView.setMinimumHeight(Math.round(containerHeight/5));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.