Skip to content

Instantly share code, notes, and snippets.

@orip
Created May 13, 2013 07:20
Show Gist options
  • Save orip/5566666 to your computer and use it in GitHub Desktop.
Save orip/5566666 to your computer and use it in GitHub Desktop.
Find all Android views tagged with a given value. Similar to document.getElementsByClassName in JavaScript/DOM to find elements with a given class. Based on this StackOverflow answer by Shlomi Schwartz: http://stackoverflow.com/a/8831593/37020
package com.onavo.android.common.ui;
import android.view.View;
import android.view.ViewGroup;
import java.util.LinkedList;
import java.util.List;
/**
* Based on http://stackoverflow.com/a/8831593/37020 by by Shlomi Schwartz
* License: MIT
*/
public class ViewGroupUtils {
public static List<View> getViewsByTag(View root, String tag) {
List<View> result = new LinkedList<View>();
if (root instanceof ViewGroup) {
final int childCount = ((ViewGroup) root).getChildCount();
for (int i = 0; i < childCount; i++) {
result.addAll(getViewsByTag(((ViewGroup) root).getChildAt(i), tag));
}
}
final Object rootTag = root.getTag();
// handle null tags, code from Guava's Objects.equal
if (tag == rootTag || (tag != null && tag.equals(rootTag))) {
result.add(root);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment