Question

I am trying to use GridLayout (not GridView!) to achieve a layout like this:

enter image description here

But with my code (and everything I tried until now) the top of two horizontally adjacent views are always aligned. Is it possible to tell the each new View to be aligned on the high-water-mark of its column instead? (see New Layout Widgets: Space and GridLayout under "Automatic Index Allocation")

My layout.xml looks like this right now:

<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"
        />

To this GridLayout I add my Views programmatically:

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

}
Was it helpful?

Solution 2

UPDATE:

Using the new RecyclerView and the StaggeredGridViewLayoutManager you can achieve this now without third-party libs.

OLD ANSWER:

I found out that this kind of View was already done by Google under the name of StaggeredGridView. It was once in the AOSP, but was taken out again (I lost the source for this info...but anyway). But you can find a modified version of StaggeredGridView here:

https://github.com/maurycyw

The original Google source is here:

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

And another very good implementation of it is found in the official Etsy App. The code was made public:

https://github.com/etsy/AndroidStaggeredGrid

OTHER TIPS

My code was similar to yours and I was running into the same issue. The problem is setting the column and row specs directly to the layoutParams once it was created. You should specify this attributes on the constructor.

Spec rowspecs = GridLayout.spec(row, 1); 
Spec colspecs = GridLayout.spec(column, 1);
GridLayout.LayoutParams gridLayoutParam = new GridLayout.LayoutParams(rowspecs, colspecs);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top