findViewById to return array of Views
I have the same View
inflated (from XML) multiple times. When I call findViewById(R.id.my_layout).setVisibility(View.GONE)
I want to开发者_JAVA技巧 apply it on all such views.
How do I do that?
There isn't a version of findViewById()
that returns all matches; it just returns the first one. You have a few options:
- Give them different ids so that you can find them all.
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); }
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.
Modify on the View
that holds the inflated layout.
E.g:
If you have
View v = inflater.inflate(.... );
you change the visibility onto this view. v.setVisibility(View.GONE);
精彩评论