GridLayout Properties Not Properly Applied When Set In Codebehind

Nathan Sokalski 4,116 Reputation points
2021-07-14T20:49:08.65+00:00

I have a GridLayout which contains several Button(s). All the Button(s) have a layout_gravity of center_horizontal, and the Button(s) in the first row have a column span of 2. In the Designer in Visual Studio 2019, this appears as follows:
114753-screenshot-2021-07-14-162718.png

In my code, I use the following code to rearrange the Button(s):

for (int btnindex = 1; btnindex < 5; btnindex++)  
{  
	(this.grdBidsKeypad.GetChildAt(btnindex).LayoutParameters as GridLayout.LayoutParams).ColumnSpec = GridLayout.InvokeSpec(btnindex - 1, 2);  
	(this.grdBidsKeypad.GetChildAt(btnindex).LayoutParameters as GridLayout.LayoutParams).RowSpec = GridLayout.InvokeSpec(0);  
}  
for (int btnindex = 5; btnindex < 10; btnindex++)  
{  
	(this.grdBidsKeypad.GetChildAt(btnindex).LayoutParameters as GridLayout.LayoutParams).ColumnSpec = GridLayout.InvokeSpec(btnindex - 5);  
	(this.grdBidsKeypad.GetChildAt(btnindex).LayoutParameters as GridLayout.LayoutParams).RowSpec = GridLayout.InvokeSpec(1);  
}  
for (int btnindex = 10; btnindex < 14; btnindex++)  
{  
	(this.grdBidsKeypad.GetChildAt(btnindex).LayoutParameters as GridLayout.LayoutParams).ColumnSpec = GridLayout.InvokeSpec(btnindex - 9);  
	(this.grdBidsKeypad.GetChildAt(btnindex).LayoutParameters as GridLayout.LayoutParams).RowSpec = GridLayout.InvokeSpec(2);  
}  
(this.grdBidsKeypad.GetChildAt(14).LayoutParameters as GridLayout.LayoutParams).ColumnSpec = GridLayout.InvokeSpec(0);  
(this.grdBidsKeypad.GetChildAt(14).LayoutParameters as GridLayout.LayoutParams).RowSpec = GridLayout.InvokeSpec(2);  
this.grdBidsKeypad.ColumnCount = 5;  
this.grdBidsKeypad.RowCount = 3;  

However, this code ends up creating the following in the emulator:
114762-screenshot-1626294503.png
It looks like either the layout_gravity is being reset or the layout_columnSpan (which, if I understand correctly, is the second parameter of InvokeSpec) is being ignored. What am I doing wrong?

Xamarin
Xamarin
A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,292 questions
{count} votes

Accepted answer
  1. Nathan Sokalski 4,116 Reputation points
    2021-09-01T03:06:40.99+00:00

    It's been a long time since I posted this question, but I finally found an answer, which hopefully can save someone else from the frustration I had. InvokeSpec requires, at least for this scenario, an alignment, such as the following:

    (this.grdBidsKeypad.GetChildAt(btnindex).LayoutParameters as GridLayout.LayoutParams).ColumnSpec = GridLayout.InvokeSpec(btnindex - 1, 2, GridLayout.Center);

    When I added GridLayout.Center to InvokeSpec on line 3 in my code above, it solved my problem.

    0 comments No comments

0 additional answers

Sort by: Most helpful