0

我正在尝试使用 GridLayout(不是 GridView!)来实现这样的布局:

在此处输入图像描述

但是使用我的代码(以及到目前为止我尝试过的所有内容),两个水平相邻视图的顶部总是对齐的。是否可以告诉每个新视图与其列的高水位线对齐?(请参阅“自动索引分配”下的新布局小部件:Space 和 GridLayout )

我的 layout.xml 现在看起来像这样:

<GridLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scroll_view_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal"
        android:columnCount="2"
        />

在这个 GridLayout 中,我以编程方式添加我的视图:

GridLayout scrollViewContainer = Views.findById(rootView, R.id.scroll_view_container);

for (i=0; i < list.size(); i++) 
  TextView tv = new TextView(context);
  tv.setText("foobar");

  GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
  // left, right, left, right - creates new default rows
  lp.columnSpec = GridLayout.spec(i%2);

  // this would put every view in the same row => all Views are on the very top
  // lp.rowSpec = GridLayout.spec(0);

  tv.setLayoutParams(lp);

  scrollViewContainer.addView(tv);

}
4

2 回答 2

1

我的代码与您的代码相似,我遇到了同样的问题。问题是在创建后将列和行规范直接设置为 layoutParams。您应该在构造函数上指定此属性。

Spec rowspecs = GridLayout.spec(row, 1); 
Spec colspecs = GridLayout.spec(column, 1);
GridLayout.LayoutParams gridLayoutParam = new GridLayout.LayoutParams(rowspecs, colspecs);
于 2013-10-28T21:11:42.120 回答
0

更新:

使用新的RecyclerViewStaggeredGridViewLayoutManager,您现在无需第三方库即可实现此目的。

旧答案:

我发现这种 View 已经被 Google 以 StaggeredGridView 的名义完成了。它曾经在 AOSP 中,但又被取出(我失去了此信息的来源……但无论如何)。但是你可以在这里找到 StaggeredGridView 的修改版本:

https://github.com/maurycyw

原始谷歌来源在这里:

https://github.com/friberry/StaggeredGridView/blob/9c4582ab8e79294ab60f63277e2a54c58e74b372/src/com/origamilabs/library/views/StaggeredGridView.java

在官方 Etsy App 中可以找到另一个非常好的实现。代码公开:

https://github.com/etsy/AndroidStaggeredGrid

于 2013-09-08T15:20:52.857 回答