Search code examples
androidandroid-linearlayout

Counting visible elements in a layout


Suppose in my LinearLayout (say parentLayout) there are 5 other LinearLayouts (say childLayout), where only one of them are visible at the moment. The other layouts depend on some external event to make them visible. How do I count the number of childLayout in the parentLayout that are visible ?


Solution

  • You can iterate over the children of the parent layout and check their visibility. Something like this:

    LinearLaout parent = ...;
    int childCount = parent.getChildCount();
    int count = 0;
    for(int i = 0; i < childCount; i++) {
        if(parent.getChildAt(i).getVisibility() == View.VISIBLE) {
            count++;
        }
    }
    System.out.println("Visible children: " + count);