findViewById返回意见的数组 [英] findViewById to return array of Views
问题描述
我有同样的查看
充气(从XML)多次。当我打电话 findViewById(R.id.my_layout).setVisibility(View.GONE)
我想它适用于所有这样的观点。
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.
我该怎么办呢?
推荐答案
有没有一个版本 findViewById()
返回所有比赛;它只是返回第一个。您有几种选择:
There isn't a version of findViewById()
that returns all matches; it just returns the first one. You have a few options:
- 给他们不同的ID,这样你可以找到他们。
-
在他们膨胀,存储在一个参考
的ArrayList
,就像这样:
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); }
根据你这些意见做什么,家长布局可能有访问它们的方法。例如,如果你把它们放在一个的ListView
或一些这样的。如果你知道你可以通过迭代儿童的父元素:
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.
这篇关于findViewById返回意见的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!