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 ?
Counting visible elements in a layout
Asked Answered
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);
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;
}
If you are using Kotlin just use extention:
fun LinearLayout.visibleChildCount(): Int {
var childVisible = 0
children.iterator().forEach {
if(it.isVisible) ++childVisible
}
return childVisible
}
© 2022 - 2024 — McMap. All rights reserved.