Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through all "widgets"/elements in a Activity

I started my own android app a few days ago since I needed a mobile application to store a bunch of data I collect in the hospital.

I'm pretty new to Java and android environment, although it seems easy to understand and very similar to C++.

Anyway, my application has a bunch of "EditText" and radio buttons and my question is:

How can I iterate through all those widgets (EditTexts and radio buttons)?

In .NET you could do a "for each element in container " loop but I can't seem to find a way to do this in Java/android environment.

Note: I don't know how many "widgets" exist in the activity, since some are created dinamicaly, others are hardcoded and some others show if some user preferences are set

Any help or hint would be appreciated.

like image 313
Tivie Avatar asked Nov 16 '10 13:11

Tivie


3 Answers

for (int i = 0; i < rootView.getChildCount(); i++)
  rootView.getChildAt(i)

Note that this will return View-s, you will have to check at runtime exactly what type of View you are currently looking at

like image 122
apps Avatar answered Oct 20 '22 03:10

apps


It works.

Regarding the View type (ie Spinner, radioButton, EditText, etc) we can tag each type we want to parse in the Layout XML file and then add a conditional, ie:

   if (Widget_Tag != null){   

      View Current_Widget = (View) rootView.getChildAt(i);          

      String Widget_Tag = (String) Current_Widget.getTag();

      if (Widget_Tag.equals("MyEdiText")) {

        //do something

      }
   }

the if (Widget_Tag != null){ is to prevent NullPointReferences. You can also doi it with a Try / Catch.

like image 36
Tivie Avatar answered Oct 20 '22 01:10

Tivie


You can try this code:

LayoutInflater inflater = getLayoutInflater();
LinearLayout l = (LinearLayout) inflater.inflate(R.layout.main, null);

ViewGroup Current_Widget = (ViewGroup)l.getRootView();

for (int i = 0; i < Current_Widget.getChildCount(); i++)
    Current_Widget.getChildAt(i);
like image 25
Vadim Zin4uk Avatar answered Oct 20 '22 03:10

Vadim Zin4uk