TableLayout的动态添加和删除
DerekSambel
9年前
AndroidTestActivity.java
package zjftools.android.test; import android.app.*; import android.os.*; import android.view.*; import android.widget.*; public class AndroidTestActivity extends Activity { private TableLayout tableLayout; private Button btnAdd; private int num = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.main); tableLayout = (TableLayout) this.findViewById(R.id.tableLayout); btnAdd = (Button) this.findViewById(R.id.btnAdd); btnAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { addRow(); num++; } }); } private void addRow() { TableRow tableRow = new TableRow(this); TextView textView = new TextView(this); Button button = new Button(this); textView.setText(String.valueOf(num)); button.setText("删除"); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { TableRow tableRow = (TableRow) view.getParent(); tableLayout.removeView(tableRow); } }); tableRow.addView(textView); tableRow.addView(button); tableLayout.addView(tableRow); } }
main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TableLayout android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" android:stretchColumns="0" android:id="@+id/tableLayout" > </TableLayout> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="add" android:id="@+id/btnAdd" /> </LinearLayout>