2010-07-25 41 views
25

我一直在尋找如何獲得TableLow的所有TableRow的小時。我已經知道如何動態添加和刪除行,但我需要遍歷所有行並有選擇地刪除其中的一些行。獲取所有TableRow的TableLayout

我想我可以想出一個解決方法,但我試圖避免在我的應用程序粗糙的黑客。

+7

-1您應該接受答案!讓人們編寫回應和代碼,然後甚至沒有看到迴應是不公平的。 – John 2014-04-04 18:06:44

+3

人們可以通過簡單的車禍或心臟病發作輕鬆過去。不要太在乎答案的接受程度等等。 – Ehsan 2015-09-21 02:50:24

回答

42

您是否嘗試過分別使用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); 
     } 
    } 
} 
+0

我沒有看到有關這些方法的Android SDK文檔中的任何內容(也許我只是忽略了它)。我會嘗試並讓你知道。 感謝您的幫助。 – eugene 2010-07-25 01:28:22

+0

@eugene絕對要注意,我沒有將這些方法引用鏈接到它們的實際sdk文檔。此外,它看起來像添加到我的答案的例子是在擴展'TableLayout'而不是使用視圖的引用,只是FYI。最後需要注意的是,如果實際上是從循環中刪除某個集合中的項目(索引重新計算等),那麼請注意。 – 2010-07-25 02:55:32

+0

順便說一句,getChildAt(int)返回'View'而不是'TableRow'! – PCoder 2012-09-28 21:24:27

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); 
    } 
} 
+1

這或多或少與[this one](http://stackoverflow.com/a/3327612)的答案相同。 – 2015-10-20 12:23:18

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. 
     } 
    } 
14

,如果您有其他類型的視圖

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); 
     } 
    } 
} 
0

如果您嘗試刪除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 = 5的行現在是ID = 4,如果你有ID = 3

所以也許刪除的行您必須重置計數器並重新迭代,或者在清除所有行後生成新表格

相關問題