Is there a way to iterate through all the views in your Activity? Something like:
Iterator it = getViewIterator();
...
Does this exi
If you have all your Views in a LinearLayout
or an other container
that extends ViewGroup
you can use the functions getChildCount()
and getChildAt(int)
and iterate through all of the
contained views.
Hope this helps.
Small recursive function which does enumerating all views
private fun processAllViews(viewGroup: ViewGroup) {
for (child in viewGroup.children) {
if (child is EditText) {
// do some stuff with EditText
} else if (child !is ViewGroup) {
// do some stuff with not EditText and not ViewGroup
} else {
processAllViews(child as ViewGroup) // process inner layout
}
}
}
Written in Kotlin.
To use this function:
processAllViews( [~rootLayoutId~] )
or if you don't have / don't want root layout id
val baseContent = (findViewById<View>(android.R.id.content) as ViewGroup).getChildAt(0) as ViewGroup
processAllViews(baseContent)
If you want to avoid the ugly for (int i = 0; ....) you can use a static wrapper
public class Tools
{
public static Iterable<View> getChildViews(final ViewGroup view)
{
return new Iterable<View>()
{
int i = -1;
@NonNull
@Override
public Iterator<View> iterator()
{
return new Iterator<View>()
{
int i = -1;
@Override
public boolean hasNext()
{
return i < view.getChildCount();
}
@Override
public View next()
{
return view.getChildAt(++i);
}
};
}
};
}
}
and use it like so
for (View view : Tools.getChildViews(viewGroup))
of course this is slightly less efficient since you are creating a new Iteratable object every time you iterate, but you could build on this a more efficient algo if you want.
If you actually need an iterator, there isn't anything like that available in the api. You'll have to write your own that is built on top of the logic that Harry Joy and Javanator suggest.
Rx java solution
public static Observable<View> iterate(@NonNull View root) {
return Observable.create(emitter -> {
iterate(root, emitter);
emitter.onComplete();
});
}
private static void iterate(@NonNull View view, @NonNull ObservableEmitter<View> emitter) {
emitter.onNext(view);
if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
iterate(viewGroup.getChildAt(i), emitter);
}
}
}
Activity Generally contains one main Layout Container in which all other views are placed. Using the reference of Main Layout Container. Traverse through its child (Use getChild(postion) , getchildcount() etc). and if any child is a container itself then apply the same function on it..This is some like traversing a tree structure