我的代码:
public class Test extends Activity {
private TableLayout tableLayout = null;
private Button add = null;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
tableLayout = (TableLayout)findViewById(R.id.tableLayout);
add = (Button)findViewById(R.id.agregar);
add.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
TableRow fila = new TableRow(Test.this);
Button eliminar = new Button(Test.this);
eliminar.setText("delete");
eliminar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
fila.addView(eliminar,new TableLayout.LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
tableLayout.addView(fila,new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
}
});
}
我希望每次点击添加 Button
时添加新行。我的xml是以下一个:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<RelativeLayout
android:id="@+id/relativelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableLayout
android:id="@+id/tableLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableRow
android:id="@+id/tableRow1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textView1"
android:text="Column 1"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="@+id/button1"
android:text="Delete" />
</TableRow>
</TableLayout>
<Button
android:id="@+id/agregar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/tableLayout"
android:text="Add" />
</RelativeLayout>
每次点击Button
,它都不会做任何事情。有人可以帮我吗?
答案 0 :(得分:0)
(在问题编辑中回答。转换为社区维基回答。请参阅What is the appropriate action when the answer to a question is added to the question itself?)
OP写道:我发现他们不能
LayoutParams
。如果他们属于TableRow
,则必须为TableRow.LayoutParams
,如果他们位于TableLayout
内,则必须为TableLayout.LayoutParams
。如下所示:eliminar.setLayoutParams(new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); fila.addView(eliminar,new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT)); tableLayout.addView(fila,new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));