androidhtmlgrid-layouthtml-tablecolumnspan

Set rowSpan or colSpan of a child of a GridLayout programmatically?


I have a GridLayout with 5 columns and 3 rows. Now I can insert arbitrary child views, which is great. Even better is, that I can assign columnSpan=2 to some item in order to span it to 2 columns (the same with rowSpan).

The problem now is, that I cannot assign rowSpan or columnSpan programmatically (i.e. at runtime). Some search suggested something like this:

layoutParams.columnSpec = GridLayout.spec(0, columnSpan);

But I don't quite understand what the parameters of spec mean (start and size). The documentation is also quite poor at this point.

Any help is highly appreciated!


Solution

  • OK, I spent some hours figuring out what's going on here. Well, I didn't find any working way to set columnSpan or rowSpan at runtime.

    But I found a solution that works (at least for me):

    Java code

    private LinearLayout addNewSpannedView(Integer resourceId, ViewGroup rootElement) {
        return (LinearLayout) ((ViewGroup) getLayoutInflater().inflate(resourceId, rootElement, true)).getChildAt(rootElement.getChildCount() - 1);
    }
    // set columnSpan depending on some logic (gridLayout is the layout to add the view's to -> in my case these are LinearLayouts)
    shape = addNewSpannedView(columnSpan == 1 ? R.layout.grid_ll_col_span_1 : R.layout.grid_ll_col_span_2, gridLayout);
    

    grid_ll_col_span_2.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="@dimen/shapeWidth"
        android:layout_height="wrap_content"
        android:layout_columnSpan="2"/>
    

    Hint: It's very important, that you set the width and height attribute, before inflate() adds the view to the root element (i.e. the parent element).

    I hope, someone can use this ;-)