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

时间:2017-02-15 17:23:39

标签: android android-recyclerview android-gridlayout

我正在尝试使此GridLayout正确显示但由于某种原因它无法正常工作。

这就是我拥有的和我想要的:

enter image description here

这是我的代码:

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);
  }
});

如果对此问题有任何疑问或者您需要更多信息,我很乐意给予:)

感谢。

2 个答案:

答案 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);

这解决了一些未知原因的错误。

注意:尽管如此,科尔提出了几乎相同的建议,但事实并非如此。如果他先读完我当前的代码,他本可以正确回答我的问题。

相关问题