2014-01-07 31 views
3

所以我在我的佈局這裏如何編程在Xamarin通過tablerow添加到TableLayout

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

定義我的佈局,它包含一個TableLayout而且我訪問它在我的代碼隱藏和試圖將一個按鈕添加到一個表格行並將該表格添加到表格中:

private TableLayout _table 
private Button _button 
. 
. 
. 
_table = FindViewById<TableLayout>(Resource.Id.table); 
_button = new Button(this){Text = "<"}; 
_button = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); 
var tableRow = new TableRow(this); 
tableRow.AddView(_button, 0); 
_table.AddView(tableRow, 0); 

問題是,當我運行我的應用程序時,tableRow不顯示出來。

+0

@羅伯特 - 沃森你有沒有得到這個固定的? – jerone

回答

8

您需要爲按鈕使用TableRow.Layoutparams ..試試這段代碼。

TableLayout _table = (TableLayout) findViewById(R.id.table); 

    LayoutParams layoutParams = new TableRow.LayoutParams(
      ViewGroup.LayoutParams.MATCH_PARENT, 
      ViewGroup.LayoutParams.MATCH_PARENT); 
    TableRow tableRow = new TableRow(this); 

    Button _button = new Button(this); 
    _button.setText(">>"); 
    _button.setLayoutParams(layoutParams); 

    tableRow.addView(_button, 0); 
    _table.addView(tableRow, 0); 
1

我重構上面的代碼,所以,這將是C#和不是Java, 享受!

TableLayout _table = (TableLayout)FindViewById(Resource.Id.tableLayout1); 

TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
     ViewGroup.LayoutParams.MatchParent, 
     ViewGroup.LayoutParams.MatchParent); 

TableRow tableRow = new TableRow(this); 

Button _button1 = new Button(this); 
_button1.Text = "1"; 
_button1.LayoutParameters = layoutParams; 

Button _button2 = new Button(this); 
_button2.Text = "2"; 
_button2.LayoutParameters = layoutParams; 

Button _button3 = new Button(this); 
_button3.Text = "3"; 
_button3.LayoutParameters = layoutParams; 

tableRow.AddView(_button1, 0); 
tableRow.AddView(_button2, 1); 
tableRow.AddView(_button3, 2); 

_table.AddView(tableRow, 0); 
1

,如果你轉換你的代碼轉換成XML它會像

<TableRow><Button /></TableRow> 

所以你要的LayoutParams添加到每個視圖創建編程

_button = new Button(this){Text = "<"}; 
_buttonparams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent,ViewGroup.LayoutParams.MatchParent); 
_button.setLayoutParams(_buttonParams); 
var tableRow = new TableRow(this); 
LayoutParams _tableRowParams = new LayoutParams(-1,-2); 
tableRow.setLayoutParam(_tableRowParams); 
tableRow.AddView(_button, 0); 
_table.AddView(tableRow, 0); 
相關問題