Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findViewById to return array of Views

Tags:

android

I have the same View inflated (from XML) multiple times. When I call findViewById(R.id.my_layout).setVisibility(View.GONE) I want to apply it on all such views.

How do I do that?

like image 738
Taranfx Avatar asked Aug 20 '11 01:08

Taranfx


1 Answers

There isn't a version of findViewById() that returns all matches; it just returns the first one. You have a few options:

  1. Give them different ids so that you can find them all.
  2. When you inflate them, store the reference in an ArrayList, like this:

    ArrayList<View> mViews = new ArrayList<View>();
    

    Then when you inflate:

    LayoutInflater inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mViews.add(inflater.inflate(R.layout.your_layout, root));
    

    Then when you want to hide them:

    for (View v : mViews) { v.setVisibility(View.GONE); }
    
  3. Depending on what you're doing with these Views, the parent layout may have a way of accessing them. E.g., if you're putting them in a ListView or some such. If you know the parent element you can iterate through the children:

    ViewGroup parent = getParentSomehow();
    for (int i = 0; i < parent.getChildCount(); ++i) {
        View v = parent.getChildAt(i);
        if (v.getId() == R.id.my_layout) {
            v.setVisibility(View.GONE);
        }
    }
    

If the above options don't work for you, please elaborate on why you're doing this.

like image 118
i_am_jorf Avatar answered Sep 30 '22 21:09

i_am_jorf