我正在尝试动态添加表格行...... 以下是我的java代码:
TableLayout tl = (TableLayout) findViewById(R.id.tablerow);
/* Create a new row to be added. */
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
/* Create a Button to be the row-content. */
Button b = new Button(this);
b.setText("Dynamic Button");
b.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
/* Add Button to row. */
tr.addView(b);
/* Add row to TableLayout. */
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
我的XML代码是
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tablerow"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<TextView
android:id="@+id/content"
android:singleLine="false" />
</TableRow>
</TableLayout>
但我在这一行得到错误:
final TableLayout tl = (TableLayout)findViewById(R.id.tablerow);
我得到的错误是无法从视图转换为TableLayout
任何帮助将不胜感激
答案 0 :(得分:1)
您需要在android:layout_height
和android:layout_width
字段中添加<TableRow>
和<TextView>
。
这两个属性是必需的。
答案 1 :(得分:0)
在为TableLayout创建实例时,检查它应该是android.widget控件..
这就是问题
TableLayout(android.widget)不是我们的包
答案 2 :(得分:0)
如何将tablerow转换为tableLayout(TableLayout)findViewById(R.id.tablerow)? 这不是错的吗?
答案 3 :(得分:0)
有两种不同类型的LayoutParams,TableRow.LayoutParams和TableLayout.LayoutParams。
如果在错误的位置使用错误的Eclipse IDE,Eclipse IDE将不会抛出错误,但这会导致UI无法正常工作。为TableRow和TableRow中的Views设置LayoutParams时,请确保使用限定名称将它们显式设置为正确。
一个例子:
TableLayout tblServices = (TableLayout) findViewById(R.id.tblServices);
TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
TextView tvName = new TextView(this);
tvName.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
tblServices.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
此外,您不需要为Button设置LayoutParams,因此删除该行应该会有所帮助。
答案 4 :(得分:0)
回答太晚,但如果有人在寻找这个。
我遇到了同样的问题并通过在尝试查找视图之前调用setContent()
来修复它。