How to clear all rows from a TableLayout?
Asked Answered
O

4

23

I know that this has already been asked before, but none of the other responses have helped me, so I'll ask myself...

I am trying to delete all my existing rows from a TableLayout because I want the user to be able to update the table dynamically. Other suggestions have recommended using removeAllViews(), which is supposed to remove all child views, however this deletes rows from my other tables in the same LinearLayout (I have a linear layout with multiple tables).

Any suggestions?

Oz answered 4/9, 2011 at 23:12 Comment(0)
B
58

It sounds like you might be calling removeAllViews() on the whole LinearLayout and not the particular TableLayout you want to clear. Double check you have some thing like:

myLinearLayout.someTableView.removeAllViews()

Britt answered 4/9, 2011 at 23:20 Comment(3)
Nope, I'm definitely calling my TableLayout... tl = (TableLayout)dialog.findViewById(R.id.afi_waist_table); tl.removeAllViews();Oz
Changed my code around a bit and was able to get removeAllViews() working.Oz
Calling removeAllViews() actually worked fine. I thought it was deleting my other tables' content because I was using a TableRow for the table header, which I didn't think I had done.Oz
R
14

You need to call removeAllViews() on each TableRow:

int count = table.getChildCount();
for (int i = 0; i < count; i++) {
    View child = table.getChildAt(i);
    if (child instanceof TableRow) ((ViewGroup) child).removeAllViews();
}
Romeu answered 5/9, 2011 at 3:55 Comment(3)
Your suggestion will remove all the subviews of the row but not the row itself. The table layout will be left with empty rows.Britt
I know, that's what I thought the original poster wanted.Romeu
great! this is fine for me :DQuincy
S
5

If you want to remove all the rows but the first row (which is often used as the header), you can use:

tableLayout.removeViews(1, Math.max(0, tableLayout.getChildCount() - 1));
Strew answered 9/9, 2020 at 20:10 Comment(0)
R
2

You can simply use yourTableView.removeViews(startIndex, count) startIndex is an integer value for where you want to start removing. Incase you have an header and don't want to remove it, start at position 1, otherwise start at 0. count is the number of row to remove.

Refractor answered 5/8, 2019 at 11:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.