在 Xamarin 中动态填充 GridLayout 的任何单元格

Dynamically filling any cell of GridLayout in Xamarin

我想动态创建一个 GridLayout,传递行数和列数并在运行时填充任何特定的网格单元格。到现在为止,我成功地制作了 2*2 的网格布局,但是当我尝试在第 2 行和第 2 列填充按钮时,默认情况下它位于第 1 行和第 1 列。

我的 objective 是将任何 UIElement(如按钮或 TextView)放置在任何网格中,方法是保持其他网格单元格为空。但我不确定如何实现这一目标。请帮助我缺少什么。

我只能从第一个开始填充 GridCell 吗?

protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);

        RelativeLayout mainlayout = new RelativeLayout(this);
        RelativeLayout.LayoutParams layoutparameter = new 
        RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MatchParent,
        RelativeLayout.LayoutParams.MatchParent);

        mainlayout.LayoutParameters = layoutparameter;

        GridLayout gl = (GridLayout)getView();
        mainlayout.AddView(gl);

        SetContentView(mainlayout);
    }



private GridLayout getView()
        {

            GridLayout gridlayout = new GridLayout(this);

            Button b = new Button(this);
            b.Text = "Button1";


            var p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, 
            ViewGroup.LayoutParams.MatchParent);
            gridlayout.LayoutParameters = p;

            gridlayout.RowCount = 2;
            gridlayout.ColumnCount = 2;

            addViewToGridLayout(gridlayout, b, 2, 1, 2, 1);

            return gridlayout;
        }



private void addViewToGridLayout(GridLayout pGridLayout, View view, int row, int pRowSpan, int column, int pColumnSpan)
    {
        Spec rowSpan = GridLayout.InvokeSpec(GridLayout.Undefined, row);
        Spec colspan = GridLayout.InvokeSpec(GridLayout.Undefined, column);
        GridLayout.LayoutParams gridParam = new GridLayout.LayoutParams(
                rowSpan, colspan);
        pGridLayout.AddView(view, gridParam);
    }
Spec rowSpan = GridLayout.InvokeSpec(GridLayout.Undefined, row,GridLayout.Center);
Spec colspan = GridLayout.InvokeSpec(GridLayout.Undefined, column, GridLayout.Center);

当您在方法 InvokeSpec 中设置 GridLayout.Undefined 时。它表示未指定列的位置。

所以需要像这样修改

Spec rowSpan = GridLayout.InvokeSpec(row,pRowSpan);
Spec colspan = GridLayout.InvokeSpec(column, pColumnSpan);

RowColumn的索引是从0开始的。当你不设置其他单元格时,单元格的默认大小将始终为 0 。因此,您可以将其他 3 个单元格的内容设置为白色 TextView,如下所示。

TextView view = new TextView(this);
view.SetMinimumHeight(350);
view.SetMinimumWidth(350);
view.SetBackgroundColor(Android.Graphics.Color.Red);

TextView view2 = new TextView(this);
view2.SetMinimumHeight(350);
view2.SetMinimumWidth(350);
view2.SetBackgroundColor(Android.Graphics.Color.Blue);

TextView view3 = new TextView(this);
view3.SetMinimumHeight(350);
view3.SetMinimumWidth(350);
view3.SetBackgroundColor(Android.Graphics.Color.Yellow);
            
addViewToGridLayout(gridlayout, view, 0, 1, 0, 1);
addViewToGridLayout(gridlayout, view2, 1, 1, 0, 1);
addViewToGridLayout(gridlayout, view3, 0, 1, 1, 1);
addViewToGridLayout(gridlayout, b, 1, 1,1, 1);