[英]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.