2012-03-09 94 views
2

动态添加的TableRow我的代码:问题与TableLayout

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,它什么都不做。有人可以帮助我吗?

+2

如果你找到了解决您的问题,请回答您的问题添加并接受它,因此问题变成了回答。 – Luksprog 2012-05-06 07:58:56

+0

如何使用FOR LOOP在tablerow中添加按钮,然后为每个按钮都会有另一个TABLEROW,它将容纳三个线性布局水平方向可以有人请帮助我吗? – nida 2013-11-19 12:11:28

回答

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));