-2
Im新的xamarin,我试图在我的主要活动中创建一个表格布局,但我不想从xml创建它。 我有一个号码,我想根据这个号码创建一个表格。如果数字可以除以2,我希望在每一行中会有2列。否则,我想创建行,每行中将有2列,最后一行中只有一列。 对不起英文不好。 thnx!以编程方式创建一个表格布局
Im新的xamarin,我试图在我的主要活动中创建一个表格布局,但我不想从xml创建它。 我有一个号码,我想根据这个号码创建一个表格。如果数字可以除以2,我希望在每一行中会有2列。否则,我想创建行,每行中将有2列,最后一行中只有一列。 对不起英文不好。 thnx!以编程方式创建一个表格布局
首先,像这样创建主布局(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的专家。机器人,但我希望这回答你的问题。祝你今天愉快。
Regards, AziziAziz