29

我一直在寻找如何在 TableLayout 中获取所有 TableRow 的几个小时。我已经知道如何动态添加和删除行,但我需要遍历所有行并有选择地删除其中一些。

我想我可以想出一个解决方法,但我试图避免在我的应用程序中出现粗暴的黑客行为。

4

5 回答 5

52

您是否尝试过分别使用getChildCount()getChildAt(int)

在循环中应该相当容易:

for(int i = 0, j = table.getChildCount(); i < j; i++) {
    View view = table.getChildAt(i);
    if (view instanceof TableRow) {
        // then, you can remove the the row you want...
        // for instance...
        TableRow row = (TableRow) view;
        if( something you want to check ) {
            table.removeViewAt(i);
            // or...
            table.removeView(row);
        }
    }
}
于 2010-07-25T01:18:34.557 回答
16

如果您有其他类型的视图

TableLayout layout = (TableLayout) findViewById(R.id.IdTable);

for (int i = 0; i < layout.getChildCount(); i++) {
    View child = layout.getChildAt(i);

    if (child instanceof TableRow) {
        TableRow row = (TableRow) child;

        for (int x = 0; x < row.getChildCount(); x++) {
            View view = row.getChildAt(x);
            view.setEnabled(false);
        }
    }
}
于 2013-11-13T06:04:57.000 回答
2

我一直在寻找同样的东西一段时间。对我来说,我一直在寻找如何检查我的表格布局中的视图。我这样做是:

    //This will iterate through your table layout and get the total amount of cells.
    for(int i = 0; i < table.getChildCount(); i++)
    {
        //Remember that .getChildAt() method returns a View, so you would have to cast a specific control.
        TableRow row = (TableRow) table.getChildAt(i); 
        //This will iterate through the table row.
        for(int j = 0; j < row.getChildCount(); j++)
        {
            Button btn = (Button) row.getChildAt(j);
            //Do what you need to do.
        }
    }
于 2013-06-25T13:31:16.607 回答
1

如果您尝试删除 TableRows,ID 计数器将减少,因此请使用此循环删除...否则,如果您不想删除,您可以使用上面的一些循环:D

    TableLayout table = (TableLayout) findViewById(R.id.tblScores);
    for(int i = 0; i < table.getChildCount(); i = 0)
    {
        View child = table.getChildAt(0);
        if (child != null && child instanceof TableRow)
        {
            TableRow row = (TableRow) child;
            row.removeAllViews();
            table.removeViewAt(i);
        }        
    }

这将清除所有行!

我认为您的主要问题是,如果您删除所有行将新放置的行,以便如果您删除 ID = 3 的行,则 ID = 5 的行现在是 ID = 4

所以也许你必须重置计数器并再次迭代,或者在清除所有行后生成新表

于 2015-03-06T13:26:51.760 回答
0
for(int i = 0, j < table.getChildCount(); i < j; i++){
    // then, you can remove the the row you want...
    // for instance...
    TableRow row = (TableRow) table.getChildAt(i);
    if( something you want to check ) {
        removeViewAt(i);
        // or...
        removeView(row);
    }
}
于 2013-01-03T14:08:39.960 回答