【问题标题】:Android Gridlayout: Add new views always on high-water-markAndroid Gridlayout:始终在高水位线上添加新视图
【发布时间】:2015-07-03 18:43:16
【问题描述】:

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

但是对于我的代码(以及到目前为止我尝试过的所有内容),两个水平相邻视图的顶部总是对齐的。是否可以告诉每个新视图与其列的高水位线对齐? (参见“自动索引分配”下的New Layout Widgets: Space and 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);

}

【问题讨论】:

    标签: android android-layout android-gridlayout


    【解决方案1】:

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

    Spec rowspecs = GridLayout.spec(row, 1); 
    Spec colspecs = GridLayout.spec(column, 1);
    GridLayout.LayoutParams gridLayoutParam = new GridLayout.LayoutParams(rowspecs, colspecs);
    

    【讨论】:

    • 什么是行,什么是列?这些是什么类型的对象?
    【解决方案2】:

    更新:

    使用新的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 应用程序中找到了另一个非常好的实现。代码已公开:

    https://github.com/etsy/AndroidStaggeredGrid

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多