开发者

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:

  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.


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);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜