how to add weight to dynamically created buttons

Hello, xamarin newb here :smile: , i made an empty TableLayout in the axml file and now im creating the rows and buttons in the main file, i want to make a minesweeper so i need a lot of buttons. i know that you can add weight in the axml file if you create the buttons there, can i do the same thing when i create them dynamically? this is what i got so far:

TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WrapContent, TableRow.LayoutParams.WrapContent);
for (int i = 0; i < size; i++)
{
    TableRow row = new TableRow(this);
    row.LayoutParameters = lp;
    for (int j = 0; j < size; j++)
    {
        Button button = new Button(this);
        button.Click += Button_Click;
        button.Text = "1";
        row.AddView(button,200,200);
    }
    tableLayout.AddView(row);
}

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    can i do the same thing when i create them dynamically?

    Set a value to initWeight and set it to Button in the loop. I've reproduced the codes and it work fines as expect.

    TableLayout tableLayout = FindViewById<TableLayout>(Resource.Id.tablelayout);
    
    TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WrapContent, TableRow.LayoutParams.WrapContent, 1.0f);
    for (int i = 0; i< size; i++)
    {
        TableRow row = new TableRow(this);
        row.LayoutParameters = lp;
        for (int j = 0; j< size; j++)
        {
            Button button = new Button(this);
            button.Click += Button_Click;
            button.LayoutParameters = lp;
            button.Text = "1";
            row.AddView(button);
        }
        tableLayout.AddView(row);
    }
    
Sign In or Register to comment.