Dynamically add rows to the TableLayout
I am trying to add table rows dynamically...... Following is my java code:
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));
My XML code is
<?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>
But I get error at this line:
final TableLayout tl = (TableLayout)findViewById(R.id.tablerow);
Error I get is Cannot cast from view to TableLayout
Any help will be appreciated
You need to have android:layout_height
and android:layout_width
in your <TableRow>
and <TextView>
fields.
Those two properties are required.
While creating an instance for TableLayout check its should be android.widget controls..
that is the problem
TableLayout(android.widget) not our package
how can you cast tablerow to tableLayout in here (TableLayout)findViewById(R.id.tablerow)? Isn't this wrong?
There are two different types of LayoutParams, TableRow.LayoutParams and TableLayout.LayoutParams.
The Eclipse IDE won't throw an error if you use the wrong one in the wrong place, but it will cause the UI to not work. When you set the LayoutParams for the TableRow and for the Views inside the TableRow, make sure that you are setting them explicitly to the right one by useing a qualified name.
An Example:
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));
Also, you don't need to set the LayoutParams for a Button, so removing that line should help.
Too late to answer but if anyone looking for this.
I had the same problem and fixed it by calling setContent()
before trying to find the view.
精彩评论