How to hide all buttons with foreach?

Asked

Viewed 102 times

0

Follows code:

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 this whole line and do up to 50 times, it is very tiring. There is a way to make a loop using foreach or for to hide all these buttons ?

1 answer

1


In a question with a similar doubt, the following solution emerged:

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 take a root layout (which contains your buttons) and you 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: https://stackoverflow.com/questions/4184889/android-refer-to-custom-views-in-a-loop/4185818#4185818

Browser other questions tagged

You are not signed in. Login or sign up in order to post.