Counting visible elements in a layout

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

+4
source share
2 answers

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

 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); 
+7
source

here is a function that returns the number of visible children in a ViewGroup, for example 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; } 
+1
source

Source: https://habr.com/ru/post/1501512/


All Articles