Shlomi Schwartz Shlomi Schwartz - 8 months ago 51
Android Question

Android - how to find multiple views with common attribute

I have a layout with multiple

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 a collection of those
s, iterate and add the listeners at run-time.

Is there a method like
that will return a collection of
s rather than just a single one?


I've finally wrote this method (Updated thanks to @SuitUp (corrected username)):

 private static ArrayList<View> getViewsByTag(ViewGroup root, String tag){
    ArrayList<View> views = new ArrayList<View>();
    final int childCount = root.getChildCount();
    for (int i = 0; i < childCount; i++) {
        final View child = root.getChildAt(i);
        if (child instanceof ViewGroup) {
            views.addAll(getViewsByTag((ViewGroup) child, tag));

        final Object tagObj = child.getTag();
        if (tagObj != null && tagObj.equals(tag)) {

    return views;

It will return all views that have android:tag="TAG_NAME" attribute. Enjoy ;)