Pei*_*ein -5 android android-recyclerview
我的任务是在屏幕上显示固定数量的项目。这并不意味着我的列表大小是固定的,而是意味着滚动时只有 5 个项目应该可见。
怎样才能做到呢?我没有找到任何关于它的有用信息。
小智 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();
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用:
# in kotlin
rcyclerView.layoutManager = MaxCountLayoutManager(context).apply { setMaxCount(5) }
Run Code Online (Sandbox Code Playgroud)
但每个项目的高度需要相同,因为我只考虑了第一个项目的高度和边距。
归档时间: |
|
查看次数: |
7776 次 |
最近记录: |