Skip to content

Instantly share code, notes, and snippets.

@mrk-han
Forked from orip/ViewGroupUtils.java
Created July 31, 2019 02:03
Show Gist options
  • Save mrk-han/2c8ac21ef52592ad493d998b4d39d01e to your computer and use it in GitHub Desktop.
Save mrk-han/2c8ac21ef52592ad493d998b4d39d01e 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