在 LinearLayout 中获取所有子项

Posted

技术标签:

【中文标题】在 LinearLayout 中获取所有子项【英文标题】:Getting all children in a LinearLayout 【发布时间】:2015-04-09 01:38:05 【问题描述】:

如何让所有孩子以后使用?

LinearLayout createRow(LinearLayout parrent, int id, int orientation, int color)
    LinearLayout cell = new LinearLayout(this);
    LinearLayout.LayoutParams rowParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.MATCH_PARENT);
    rowParams.weight = 1;
    rowParams.setMargins(5,2,5,2);

    cell.setLayoutParams(rowParams);

    cell.setBackgroundColor(color);
    cell.setOrientation(orientation);
    cell.setId(id);

    parrent.addView(cell);

    cell.setOnClickListener(cellListener);
    return cell;

【问题讨论】:

【参考方案1】:

您可以使用getChildCount() 获取布局中的子级数量 一旦你有了它,你可以像这样循环它们:

int childCount = cell.getChildCount();
View child;
for(int i=0; i++; i<childCount)

   child = cell.getChildAt(i);
   // do what you want with each child element

【讨论】:

以上是关于在 LinearLayout 中获取所有子项的主要内容,如果未能解决你的问题,请参考以下文章