如何在Xamarin中编程添加一个tableRow到TableLayout

4

所以我有一个包含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>

我正在代码后端访问它,并尝试将一个按钮添加到表行中,然后将该表行添加到表格中:

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没有显示出来。

@robert-watson 你最终解决了这个问题吗? - jerone
3个回答

10

您需要使用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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接