main.xml: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas./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> ======================== MainActivity.java: package com.example.lzd.myapplication; import android.app.*; import android.os.*; import android.view.*; import android.widget.*;
public class MainActivity extends AppCompatActivity { private TableLayout tableLayout; private Button btnAdd; private int num = 0;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_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); } }
|