当前位置: 代码迷 >> Android >> 具有不同大小的正方形的GridLayout无法正确显示
  详细解决方案

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

热度:33   发布时间:2023-08-04 11:18:31.0

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

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

谢谢。

我认为,可以使用自定义视图包装项目视图。在自定义视图中,应覆盖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周真是太愚蠢了,可是在这里。 与其在CustomAdapterOnCreateViewHolder中调用函数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);

由于某些未知原因,此错误已修复。

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