Counting visible elements in a layout
Asked Answered
T

3

7

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 ?

Tinsel answered 10/9, 2013 at 16:10 Comment(0)
S
11

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);
Safari answered 10/9, 2013 at 16:18 Comment(0)
F
2

here is a funntion that returns number of visible childs in ViewGroup like LinearLayout, RelativeLayout, ScrollView, ..etc

private int countVisible(ViewGroup myLayout)
{
    if(myLayout==null) return 0;
    int count = 0;
    for(int i=0;i<myLayout.getChildCount();i++)
    {
        if(myLayout.getChildAt(i).getVisibility()==View.VISIBLE)
            count++;
    }
    return count;
}
Framboise answered 10/9, 2013 at 16:18 Comment(0)
T
0

If you are using Kotlin just use extention:

fun LinearLayout.visibleChildCount(): Int {
  var childVisible = 0
  children.iterator().forEach {
      if(it.isVisible) ++childVisible
  }
  return childVisible
}
Turenne answered 2/9, 2022 at 9:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.