所以我的布局包含在我的布局中定义的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>
我在我的代码隐藏中访问它并尝试向表行添加一个按钮并将该tablerow添加到表中:
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 :(得分:9)
您需要使用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 :(得分: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);
答案 2 :(得分: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);