分享

TableLayout动态添加和删除行

 昵称29079058 2016-09-20
 
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);
}
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约