在 Xamarin.Android 的 GridLayout 中以编程方式设置子项的列号

问题描述

在我的 Xamarin.Android 项目中,我有一个 GridLayout 和两个按钮,它们是布局的子项。现在我想通过代码设置 GridLayout 中按钮的位置。我找不到合适的方法来做到这一点,所以请帮忙。

解决方法

你可以这样做:

LinearLayout linear = FindViewById<LinearLayout>(Resource.Id.linearlayout);
GridLayout gridLayout = new GridLayout(this);
gridLayout.RowCount = 1;
gridLayout.ColumnCount = 2;
GridLayout.LayoutParams layoutParams1 = new GridLayout.LayoutParams(GridLayout.InvokeSpec(0),GridLayout.InvokeSpec(0)); //The first parameter constrains the position of the row,and the second parameter constrains the position of the column
GridLayout.LayoutParams layoutParams2 = new GridLayout.LayoutParams(GridLayout.InvokeSpec(0),GridLayout.InvokeSpec(1));
       
Button button1 = new Button(this);
button1.Text = "AA";
Button button2 = new Button(this);
button2.Text = "BB";
      
gridLayout.AddView(button1,layoutParams1);
gridLayout.AddView(button2,layoutParams2);
        
linear.AddView(gridLayout);