0

How can I programmatically create and add views to a GridLayout using C# in Xamarin.Android, while specifying column/row span?

1 Answer 1

0

You can do this while specifying column and row span, however the process of doing this in C# is different from Java. To create the GridLayout:

//Create the Grid Layout with 2 rows and 2 columns.
GridLayout sampleGridLayout = new GridLayout(mainActivity);
sampleGridLayout.RowCount = 2;
sampleGridLayout.ColumnCount = 2;

//Assuming you're adding the GridLayout to a LinearLayout. 
//Replace the layout parameters as needed.
var gridLayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.WrapContent);
sampleGridLayout.LayoutParameters = gridLayoutParameters;

//Create a Text View.
TextView sampleTextView1 = new TextView(mainActivity);
sampleTextView1.Text = "Sample Text 1";
//The GridLayout.LayoutParams constructor being used is this:
//GridLayout.LayoutParams(GridLayout.Spec? rowSpec, GridLayout.Spec? columnSpec)
//When invoking "Spec", the first integer is the 0 based column/row index(what row/column the view is in), the 2nd integer is the column/row span.
//So this is putting it in the first row, first column, only spanning a single cell.
var sampleTextView1Parameters = new GridLayout.LayoutParams(GridLayout.InvokeSpec(0, 1), GridLayout.InvokeSpec(0, 1));
sampleTextView1.LayoutParameters = sampleTextView1Parameters;

//Create a second Text View.
TextView sampleTextView2 = new TextView(mainActivity);
sampleTextView2.Text = "Sample Text 2";
//This is putting it in the first row, second column, only spanning a single cell.
var sampleTextView2Parameters = new GridLayout.LayoutParams(GridLayout.InvokeSpec(0, 1), GridLayout.InvokeSpec(1, 1));
sampleTextView2.LayoutParameters = sampleTextView2Parameters;

//Create a third Text View.
TextView sampleTextView3 = new TextView(mainActivity);
sampleTextView3.Text = "Sample Text 3";
//This is putting it in the second row, first column, but it spans both columns.
var sampleTextView3Parameters = new GridLayout.LayoutParams(GridLayout.InvokeSpec(1, 1), GridLayout.InvokeSpec(0, 2));
sampleTextView3.LayoutParameters = sampleTextView3Parameters;

sampleGridLayout.AddView(sampleTextView1);
sampleGridLayout.AddView(sampleTextView2);
sampleGridLayout.AddView(sampleTextView3);

This will create a GridLayout where the first row has two TextViews side by side, while the second row is a single TextView that spans both columns.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.