具有不同大小正方形的 GridLayout 无法正确显示

GridLayout with different sized Squares not displaying correctly

我正在尝试使此 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);
  }
});

如果对这个问题有任何疑问或者您需要更多信息,我很乐意提供:)

谢谢。

在我看来,您可以使用自定义视图将项目 view.And 包裹在自定义视图中,您应该覆盖 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;
            }  

  });  

管理员会自动为每个项目设置宽度和高度,因此您无需手动设置

经过近一周的努力,我找到了解决办法。我在这样的事情上浪费了 1 周时间是非常愚蠢的,但就是这样。而不是在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);

这修复了错误,原因不明。

注意: 尽管 Cole 提出了几乎相同的建议,但它与问题无关。如果他先阅读我当前的代码,他本可以正确回答我的问题。