我正在尝试使此GridLayout正确显示但由于某种原因它无法正常工作。
这就是我拥有的和我想要的:
这是我的代码:
GridLayoutManager lm = new GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false);
mCustomView.setLayoutManager(lm);
mCustomAdapter = new CustomAdapter(imagesList);
mCustomView.setAdapter(mCustomAdapter);
并且位于 CustomAdapter
中的 OnCreateViewHolder 下itemView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
@Override
public void onGlobalLayout() {
final GridLayoutManager lm = (GridLayoutManager) ((RecyclerView) parent).getLayoutManager();
lm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
int mod = position % 4;
if(mod == 1 || mod == 2)
return 1;
else
return 2;
}
});
int pLength = itemView.getWidth();
ViewGroup.LayoutParams pParams = itemView.getLayoutParams();
pParams.width = pLength;
pParams.height = pLength;
itemView.setLayoutParams(pParams);
itemView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
如果对此问题有任何疑问或者您需要更多信息,我很乐意给予:)
感谢。
答案 0 :(得分:0)
在我看来,您可以使用自定义视图来包装项目视图。在自定义视图中,您应该覆盖onMeasure
方法:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// set your width and height
setMeasuredDimension(width, height);
}
创建layoutManager
时:
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
if( position % 4 == 1 || position %4 ==2)
return 1;
else
return 2;
}
});
管理员会自动设置每个项目的宽度和高度,因此您不需要设置manualy
答案 1 :(得分:0)
经过近一周的奋斗,我找到了解决办法。我在这样的事情上浪费了一周是非常愚蠢的,但现在就是这样。而不是在 CustomAdapter 中的 OnCreateViewHolder 中调用函数 setSpanSizeLookup(),而在调用适配器时应将其称为 即
GridLayoutManager lm = new GridLayoutManager(context, 3, GridLayoutManager.VERTICAL, false);
lm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
int mod = position % 4;
if(mod == 1 || mod == 2)
return 1;
else
return 2;
}
});
mCustomView.setLayoutManager(lm);
mCustomAdapter = new CustomAdapter(imagesList);
mCustomView.setAdapter(mCustomAdapter);
这解决了一些未知原因的错误。
注意:尽管如此,科尔提出了几乎相同的建议,但事实并非如此。如果他先读完我当前的代码,他本可以正确回答我的问题。