2012-03-09 96 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));