在 GridLayoutManager 中,我能够设置跨度计数,这使得 View 内的项目可以调整大小,以便能够水平适应该跨度计数。
我有一个 LinearLayoutManager,我想以同样的方式使用它,让固定数量的项目可见并调整它们的大小以适应。
我在同一 View 中同时使用线性和网格,并根据屏幕大小显示项目。我似乎找不到让两种布局显示相同数量项目的方法。
最佳答案
已更新
我之前的答案是使用 ItemsAdapter 来设置每个项目的宽度,从代码设计的角度来看,这不是最好的解决方案。 正确的做法是扩展 LinearLayoutManager,因为布局项目 View 是 LayoutManager 的职责。
要点:https://gist.github.com/modjke/b652021679a2ed1935645a18102ab799
代码:
//usage:
//int itemsPerPage = 7;
//layoutManager = new LinearLayoutPagerManager(context, LinearLayoutManager.HORIZONTAL, false, itemsPerPage);
//recyclerView.setLayoutManager(layoutManager);
public class LinearLayoutPagerManager extends LinearLayoutManager {
private int mItemsPerPage;
public int getItemsPerPage()
{
return mItemsPerPage;
}
public LinearLayoutPagerManager(Context context, int orientation, boolean reverseLayout, int itemsPerPage) {
super(context, orientation, reverseLayout);
mItemsPerPage = itemsPerPage;
}
@Override
public boolean checkLayoutParams(RecyclerView.LayoutParams lp) {
return super.checkLayoutParams(lp) && lp.width == getItemSize();
}
@Override
public RecyclerView.LayoutParams generateDefaultLayoutParams() {
return setProperItemSize(super.generateDefaultLayoutParams());
}
@Override
public RecyclerView.LayoutParams generateLayoutParams(ViewGroup.LayoutParams lp) {
return setProperItemSize(super.generateLayoutParams(lp));
}
private RecyclerView.LayoutParams setProperItemSize(RecyclerView.LayoutParams lp) {
int itemSize = getItemSize();
if (getOrientation() == HORIZONTAL) {
lp.width = itemSize;
} else {
lp.height = itemSize;
}
return lp;
}
private int getItemSize() {
int pageSize = getOrientation() == HORIZONTAL ? getWidth() : getHeight();
return Math.round((float) pageSize / mItemsPerPage);
}
上一个答案
您可以通过为每个项目提供宽度来在您的适配器中设置准确的项目计数。这仅在所有项目宽度相等时才有效,不要忘记设置
recyclerView.setHasFixedSize(true);
在你的 RecyclerView 上
final static int ITEMS_PER_PAGE = 7;
@Override
public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int itemWidth = parent.getWidth() / ITEMS_PER_PAGE;
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.your_layout, parent, false);
ViewGroup.LayoutParams layoutParams = itemView.getLayoutParams();
layoutParams.width = itemWidth;
itemView.setLayoutParams(layoutParams);
return new ItemViewHolder(itemView);
}
关于android - RecyclerView LinearLayoutManager 设置项目计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36635442/