Android - how to find multiple views with common attribute

后端 未结 8 1884
野趣味
野趣味 2020-12-05 02:28

I have a layout with multiple ImageViews, some of those images need to have the same onClickListener. I would like my code to be flexible and to be able to get

8条回答
  •  有刺的猬
    2020-12-05 02:50

    This is a modification of Shlomi Schwartz's answer above. All credit to them. I didn't like how the recursion looked, and needed to be able to regex match a string tag name.

      /**
       * Find all views with (string) tags matching the given pattern.
       *
       */
      protected static Collection findViewsByTag(View root, String tagPattern) {
        List views = new ArrayList<>();
    
        final Object tagObj = root.getTag();
        if (tagObj instanceof String) {
          String tagString = (String) tagObj;
          if (tagString.matches(tagPattern)) {
            views.add(root);
          }
        }
    
        if (root instanceof ViewGroup) {
          ViewGroup vg = (ViewGroup) root;
          for (int i = 0; i < vg.getChildCount(); i++) {
            views.addAll(findViewsByTag(vg.getChildAt(i), tagPattern));
          }
        }
    
        return views;
      }
    

    For example:

    Collection itemNameViews = findViewsByTag(v, "^item_name_[0-9]+$");
    

提交回复
热议问题