2013-10-16 115 views
1

我有一個TableLayout在TableLayout添加行的onClick事件

<TableLayout 
android:id="@+id/tableLayout1" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:shrinkColumns="*" 
android:stretchColumns="*" > 

<TableRow 
android:id="@+id/tableRow2" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" > 

    <TextView 
     android:id="@+id/textView2" 
     android:text="Day High" 
     android:textStyle="bold" > 
    </TextView> 

    <TextView 
     android:id="@+id/textView3" 
     android:gravity="center_horizontal" 
     android:text="28°F" > 
    </TextView> 

    <TextView 
     android:id="@+id/textView4" 
     android:gravity="center_horizontal" 
     android:text="26°F" > 
    </TextView>  

</TableRow> 
</TableLayout> 

並有Button

<Button 
android:id="@+id/addItemTableRow" 
style="?android:attr/buttonStyleSmall" 
android:layout_width="match_parent" 
android:layout_height="31dp" 
android:textColor="@android:color/white" 
android:text="Add row" /> 

我沒有得到通過點擊button盡在添加一個新行表。

任何想法我怎麼能實現這個任務?

+0

您是否嘗試過創建一個新的TableRow和編程的TextView? –

+0

是的,我試圖以編程方式創建它們 – user2887315

+0

因此,請展示您的代碼並解釋它爲什麼沒有按預期工作。 –

回答

1

試試這個你對自己的活動類的onCreate方法:

//define a onClickListener for your button 
    Button btnAddItem = (Button) findViewById(R.id.addItemTableRow); 
    btnAddItem.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View v) { 
          //create a new row to add 
      TableRow row = new TableRow(YourActivity.this); 
          //add Layouts to your new row 
      TextView txt = new TextView(YourActivity.this); 
      txt.setText("New Row"); 
      row.addView(txt); 
      //add your new row to the TableLayout: 
      TableLayout table = (TableLayout) findViewById(R.id.tableLayout1); 
      table.addView(row); 

     } 
    });