I have a layout with multiple ImageView
s, some of those images need to have the same onClickListener.
I would like my code to be flexible and to be able to get
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]+$");