How to set layout_weight programmatically?

Disclaimer: AFAIK This question has no answer so far for XAMARIN ANDROID. It has been answered multiple times for Android/Java.

My problem is that I have no constructor overload for GridLayoutParams that takes the layout_weight as a parameter...

The following is the XML I'm trying to replicate by code:


Not setting layout_weight makes the control (a checkbox) simply invisible.

Here is where I am with the Xamarin Android code:

            CheckBox cb = new CheckBox(this);
            cb.Id = View.GenerateViewId();
            GridLayout.LayoutParams cbButtonLayoutParams = new GridLayout.LayoutParams();
            cbButtonLayoutParams.RowSpec = GridLayout.InvokeSpec(row, 1);   // Setting row and rowspan respectivly
            cbButtonLayoutParams.ColumnSpec = GridLayout.InvokeSpec(column, 1);    // Setting col and colspan respectivley
            cbButtonLayoutParams.Width = 0;
            cbButtonLayoutParams.Height = GridLayout.LayoutParams.WrapContent;
            // How do I set the weight ? There is no property nor constructor...
            // cbButtonLayoutParams.???
            cb.LayoutParameters = cbButtonLayoutParams;

Any help appreciated.

1 answer

  • answered 2018-11-09 17:34 TheWanderer

    It's under the respective Spec.

    cbButtonLayoutParams.RowSpec.weight = 1; //might be Weight in C#
    cbButtonLayoutParams.ColumnSpec.weight = 1;

    I'm not sure if you want the row weight or the column weight, but that's how you do it for both.


    I believe that InvokeSpec() is equivalent to spec(), which means the second parameter should be the weight, as long as both parameters are Int32.

    Also, layout_weight is usually only for when the parent of that element is a LinearLayout. Are you sure that the CheckBox is actually being added to the GridLayout and not a LinearLayout child?