This question already has answers here:
How to add rows dynamically into table layout
                                
                                    (5个答案)
                                
                        
                                6年前关闭。
            
                    
我有一个TableLayout

<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在表中添加新行。

有什么想法可以执行此任务吗?

最佳答案

在您的Activity类的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);

        }
    });

10-07 19:33
查看更多