Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - how to find multiple views with common attribute

Tags:

android

view

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

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

like image 708
Shlomi Schwartz Avatar asked Jan 11 '12 10:01

Shlomi Schwartz


2 Answers

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)) {             views.add(child);         }      }     return views; } 

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

like image 59
Shlomi Schwartz Avatar answered Oct 03 '22 00:10

Shlomi Schwartz


Shlomi Schwartz's method has one flaw, it does not collect Views wchich are ViewGroups. Here is my fix:

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)) {             views.add(child);         }      }     return views; } 
like image 24
SuitUp Avatar answered Oct 02 '22 23:10

SuitUp