以编程方式创建tablelayout

时间:2016-11-27 16:53:03

标签: android xamarin.android

我是xamarin的新手,我试图在我的主要活动中创建一个表格布局,但我不想从xml创建它。 我有一个号码,我想基于这个号码创建一个表。如果数字可以除以2,我希望每行中有2个列。否则,我想创建每行中有2个列的行,而在最后一行只创建一个列。 抱歉英语不好。 日Thnx!

1 个答案:

答案 0 :(得分:1)

首先,像这样创建主要布局(Main.axml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px" />

然后在你的MainActivity.cs中执行以下操作:

LinearLayout mainLayout = FindViewById<LinearLayout>(Resource.Id.mainLayout); //get your linearlayout from your Main.axml
TableLayout table = new TableLayout(this); //create a new tablelayout
mainLayout.AddView(table); //add your tablelayout to your mainlayout

int number = 19;

for (int i = 0; i < number; i++)
{
    TableRow row = new TableRow(this); //create a new tablerow
    row.SetGravity(GravityFlags.Center); //set it to be center (you can remove this if you don't want the row to be in the center)
    TextView column1 = new TextView(this); //create a new textview for left column
    TextView column2 = new TextView(this); //create a new textview for right column

    if (number % 2 == 0) //if your number is even
    {
        column1.Text = "Details " + ++i; //insert text in the first textview
        column2.Text = "Details " + (i + 1); //insert text in the second textview
        row.AddView(column1); //add the first textview to your tablerow (left column)
        row.AddView(column2); //add the second textview to your tablerow (right column)
        table.AddView(row); //add the tablerow to your tablelayout
    }

    else //if your number is odd
    {
        column1.Text = "Details " + ++i;
        row.AddView(column1);

        if (i != number) //if it is not the last item, add another (right) column
        {
            column2.Text = "Details " + (i + 1);
            row.AddView(column2);
        }

        table.AddView(row);
    }
}

我不是Xamarin.android的专家,但我希望这能回答你的问题。祝你有愉快的一天。

此致 AziziAziz