以编程方式将视图添加到 Xamarin.Android C# 中的 GridLayout
Posted
技术标签:
【中文标题】以编程方式将视图添加到 Xamarin.Android C# 中的 GridLayout【英文标题】:Programmatically add view to a GridLayout in Xamarin.Android C# 【发布时间】:2021-12-02 06:06:16 【问题描述】:如何在 Xamarin.android 中使用 C# 以编程方式创建视图并将其添加到 GridLayout,同时指定列/行跨度?
【问题讨论】:
【参考方案1】:您可以在指定列和行跨度时执行此操作,但是在 C# 中执行此操作的过程与 Java 不同。创建 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);
这将创建一个 GridLayout,其中第一行有两个并排的 TextView,而第二行是跨越两列的单个 TextView。
【讨论】:
以上是关于以编程方式将视图添加到 Xamarin.Android C# 中的 GridLayout的主要内容,如果未能解决你的问题,请参考以下文章
以编程方式将 XIB 视图添加到具有边界的视图控制器 - 不居中