如何在android中动态删除TableRow

时间:2013-12-27 02:06:23

标签: java android

在我的程序中,我动态添加一个TableRow,每行有2个TextView和一个Button。单击该按钮时,我想删除该行。

这是我用来动态制作TableRows并将它们添加到TableLayout的代码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_delete);

    // Show the Up button in the action bar.
    setupActionBar();
    Intent intent = getIntent();
    Bundle bundle = intent.getExtras();
    ArrayList <Item> items = (ArrayList <Item>) bundle.getSerializable("array");
    TableLayout layout = (TableLayout) findViewById(R.id.tl);




    for(int i=0; i<items.size(); i++)
    {

        Item item = items.get(i);

        TextView name = new TextView(this);
        TextView price = new TextView(this);
        Button delete = new Button(this);
        delete.setText("Delete");
        delete.setOnClickListener(click);
        row = new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
         row.setLayoutParams(lp);

        name.setText(item.getName());
        price.setText(Double.toString(item.getPrice()));
        row.addView(name);
        row.addView(price);
        row.addView(delete);

        layout.addView(row, i);


    }





}

如何实现OnClickListener以便删除删除按钮所在的相应行?

2 个答案:

答案 0 :(得分:0)

TableLayout继承自ViewGroup,因此removeView(View view)removeViewAt(int index)removeAllViews()等方法可以正常使用。

设置onClickListener,类似于:

Button delete = new Button(this);
delete.setText("Delete");
delete.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // Use getParent() to get the parent view which will be a LinearLayout
        // (A TableLayout is made up of LinearLayouts representing each row)
        // You can then use indexOfChild(View child) to get the index of the 
        // LinearLayout child in the TableLayout
    }
});

答案 1 :(得分:0)

按如下方式更新您的代码:

final TableLayout layout = (TableLayout) findViewById(R.id.tableLayout);

for(int i=0; i<items.size(); i++) {

    Item item = items.get(i);

    final TableRow row = new TableRow(this);
    TableRow.LayoutParams lp = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
    row.setLayoutParams(lp);

    TextView name = new TextView(this);
    TextView price = new TextView(this);
    Button delete = new Button(this);
    delete.setText("Delete");
    delete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            layout.removeView(row);
        }
    });

    name.setText(item.getName());
    price.setText(Double.toString(item.getPrice()));
    row.addView(name);
    row.addView(price);
    row.addView(delete);

    layout.addView(row, i);
}

我添加了onClickListenerrowlayout是最终变量。这有效!