在 Android 开发中,有时需要在一个表格中动态地添加一行或多行数据,这时就需要用到 TableRow 控件。本文将介绍如何通过点击按钮来添加 TableRow 的源码。首先,在布局文件中添加一个 TableLayout 控件和一个 Button 控件,如下所示:```xml android:id="@+id/tableLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:stretchColumns="*"> android:id="@+id/addRowButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="添加行" />```然后,在 Activity 中获取这两个控件,并为 Button 添加点击事件监听器,如下所示:```javaTableLayout tableLayout = findViewById(R.id.tableLayout);Button addRowButton = findViewById(R.id.addRowButton);addRowButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 添加一行数据 TableRow tableRow = new TableRow(MainActivity.this); TextView textView1 = new TextView(MainActivity.this); TextView textView2 = new TextView(MainActivity.this); textView1.setText("数据1"); textView2.setText("数据2"); tableRow.addView(textView1); tableRow.addView(textView2); tableLayout.addView(tableRow); }});```在点击事件监听器中,首先创建一个 TableRow 控件和两个 TextView 控件,并设置 TextView 的文本。然后将 TextView 添加到 TableRow 中,最后将 TableRow 添加到 TableLayout 中。这样,每次点击按钮都会在 TableLayout 中添加一行数据。总结:通过本文的介绍,我们了解了在 Android 中如何通过点击按钮来动态添加 TableRow 控件的源码。在实际开发中,我们可以根据需求对这段代码进行修改和扩展,以适应不同的业务需求。