How to hide all buttons with foreach?

0

Follow the code below:

FindViewById<Button>(Resource.Id.Button_1).Visibility = ViewStates.Gone;

The code above is to hide a "button 1" and I have more than 50 buttons. I do not want to copy all this line and do up to 50 times, it's very tiring. Is there a way to loop through foreach or for to hide all those buttons?

    
asked by anonymous 25.03.2018 / 05:13

1 answer

1

In a question with a similar question, the following solution appeared:

ViewGroup group = findViewById(R.id.root); // The name of your layout
int children = group.getChildCount();
for (int i = 0; i < children; i++) {

    View child = group.getChildAt(i);
    if (child instanceof ViewOne) {        
       ... 
    } else if (child instanceof ViewTwo) {
       ...
    }
}

In which you get a root layout (which contains your buttons) and can iterate over them. In your case it would look something like:

ViewGroup viewGroup = FindViewById<ViewGroup>(Resource.Id.root);
int children = viewGroup.ChildCount;
for (int i = 0; i < children; i++)
{
    string buttonID = "btn" + i;
    int resID = Resources.GetIdentifier(buttonID, "id", PackageName);
    FindViewById<Button>(resID).Visibility = ViewStates.Gone;

}

Source: link

    
25.03.2018 / 06:03