Search code examples
javaandroidandroid-layoutandroid-linearlayoutprogrammatically-created

Getting all children in a LinearLayout


How to get all children in order to use them later?

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

Solution

  • You can get the number of children on your layout using the getChildCount() Once you have that you can loop through them like this:

    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
    }