How to iterate through a view's elements

AndroidForms

Android Problem Overview


I have a view with radios, inputs and a button and when I click it, I want to check that all inputs contain information. How can I iterate through the view's elements in the activity and check if every textview meets the aforementioned requirement ? Thanks.

Android Solutions


Solution 1 - Android

I've done something similar in some code I don't have with me at the moment, but from memory it should be something like this (assuming a parent view LinearLayout with an id of "layout"):

LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
boolean success = formIsValid(layout);

public boolean formIsValid(LinearLayout layout) {
	for (int i = 0; i < layout.getChildCount(); i++) {
		View v = layout.getChildAt(i);
		if (v instanceof EditText) {
			//validate your EditText here
		} else if (v instanceof RadioButton) {
			//validate RadioButton
		} //etc. If it fails anywhere, just return false.
	}
	return true;
}

Solution 2 - Android

To apply the method by kcoppock recursively, you can change it to this:

private void loopViews(ViewGroup view) {
    for (int i = 0; i < view.getChildCount(); i++) {
        View v = view.getChildAt(i);
      
        if (v instanceof EditText) {
            // Do something

        } else if (v instanceof ViewGroup) {
           
            this.loopViews((ViewGroup) v);
        }
    }
} 

Solution 3 - Android

If you are writing in Kotlin, Android Jetpack's Kotlin extensions (KTX) provide extension functions for iterating over a ViewGroup's children.

myViewGroup.forEach { ... }

myViewGroup.forEachIndexed { index, view -> ... }

Just add the dependency to your app. Check the link above to get the most up-to-date version.

implementation "androidx.core:core-ktx:1.2.0"

These extensions contains hoards of useful functions otherwise chalked up as boilerplate. Worth checking out now to save time in the future!

Solution 4 - Android

Your onClickListener supplies the View v object; use View rV = v.getRootView() to position yourself on the form. Then use rV.findViewWithTag( ... ) or rV.findViewByID(R.id. ... ) to locate your form elements.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionxainView Question on Stackoverflow
Solution 1 - AndroidKevin CoppockView Answer on Stackoverflow
Solution 2 - AndroidKalimahView Answer on Stackoverflow
Solution 3 - AndroidM. PalsichView Answer on Stackoverflow
Solution 4 - AndroidgssiView Answer on Stackoverflow