2016-11-27 81 views
-2

Im新的xamarin,我試圖在我的主要活動中創建一個表格佈局,但我不想從xml創建它。 我有一個號碼,我想根據這個號碼創建一個表格。如果數字可以除以2,我希望在每一行中會有2列。否則,我想創建行,每行中將有2列,最後一行中只有一列。 對不起英文不好。 thnx!以編程方式創建一個表格佈局

回答

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的專家。機器人,但我希望這回答你的問題。祝你今天愉快。

Regards, AziziAziz

相關問題