Search code examples
javaandroidwidgettogglebutton

Loop through Togglebuttons in Activity


I'm looking to loop through all the Togglebuttons I have in one activity and do one of two things. In one case I want to set their values, in another case I want to read their values. Is the easiest way to do this to loop through the children, try to check their type for togglebutton and then preform the previously mentioned tasks?

Would I use something like this?

     for (int i = 0; i < rootView.getChildCount(); i++)
       if (Widget_Tag != null){   
       View Current_Widget = (View) rootView.getChildAt(i);          
       String Widget_Tag = (String) Current_Widget.getTag();
       if (Widget_Tag.equals("MyToggleButton")) {
         //do something
       }
     }

******UPDATE******

Working code as follows (thanks for answer), I nested another for-loop to dig down one child layer for my ToggleButtons:

    ViewGroup rootView = (ViewGroup) findViewById(R.id.LayoutHere);
    for (int i = 0; i < rootView.getChildCount(); i++) {
      ViewGroup nextLayout = (ViewGroup) rootView.getChildAt(i);
      for (int i2 = 0; i2 < nextLayout.getChildCount(); i2++) {
          View Current_Widget = nextLayout.getChildAt(i2);          
            if(Current_Widget instanceof ToggleButton) 
            {                     
              //Do Something
            }                         
      }         
    }

Solution

  • What you are doing would work if you have tagged your ToggleButton's with the String "MyToggleButton" like this:

    ToggleButton button = getSomeToggleButton();
    button.setTag("MyToggleButton");
    

    If you have not done something like the above previously, then your code snippet will not work. You could do an instanceof check on each View.

    if(Current_Widget instanceof ToggleButton) {// or instanceof MyToggleButton if that is a class of yours...
        //do something
    }