【发布时间】:2017-08-30 12:29:46
【问题描述】:
我的任务是在屏幕上显示固定数量的项目。 这并不意味着我有固定大小的列表,这意味着滚动时应该只有 5 个项目可见。
如何实现? 我没有找到任何有用的信息。
【问题讨论】:
标签: android android-recyclerview
我的任务是在屏幕上显示固定数量的项目。 这并不意味着我有固定大小的列表,这意味着滚动时应该只有 5 个项目可见。
如何实现? 我没有找到任何有用的信息。
【问题讨论】:
标签: android android-recyclerview
我也遇到了类似的问题。我几乎完美地解决了它。我选择扩展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 返回正确的像素值
如果我正确地回答了您的问题,那么每当用户停止滚动时,您就会尝试在屏幕上显示固定数量的列表项。
这可以通过计算屏幕高度/宽度,然后相应地设置列表项布局尺寸(高度/宽度)来完成。
view.getLayoutParams().width = getScreenWidth() / VIEWS_COUNT_TO_DISPLAY;
现在,根据您想要水平列表还是垂直列表,更改列表项布局的宽度或高度值。
检查这些链接
【讨论】:
最简单的解决方案是让onBindViewHolder() 动态设置其视图高度/宽度。对于垂直列表:
float containerHeight = mRecyclerView.getHeight();
holder.itemView.setMinimumHeight(Math.round(containerHeight/5));
【讨论】: