ajay ajay - 25 days ago 6
Android Question

Delete row dynamically from table layout in android

I am having a

TableLayout
for which I added rows dynamically. In each of the row there are 2 elements of which one is
TextView
other is
Button
. When I click the button that is present in a row, that row should be deleted. How can this be done in Android ? How to find rowid and how to delete a row dynamically. Can anyone help me in sorting out this issue.

Answer

onClick on the button will give you the clicked view, the button in your case. That button's parent is the row you want to delete. Deleting that row from it's parent will get rid of it.

An example of how you could implement this:

    button.setOnClickListener(new OnClickListener()
    {
        @Override public void onClick(View v)
        {
            // row is your row, the parent of the clicked button
            View row = (View) v.getParent();
            // container contains all the rows, you could keep a variable somewhere else to the container which you can refer to here
            ViewGroup container = ((ViewGroup)row.getParent());
            // delete the row and invalidate your view so it gets redrawn
            container.removeView(row);
            container.invalidate();
        }
    });