Skip to content

Instantly share code, notes, and snippets.

@jsaund
Last active March 2, 2016 06:47
Show Gist options
  • Select an option

  • Save jsaund/851a8137e05d3f237034 to your computer and use it in GitHub Desktop.

Select an option

Save jsaund/851a8137e05d3f237034 to your computer and use it in GitHub Desktop.
A utility to dump the Android view hierarchy and detect duplicate resource IDs in the hierarchy
public class ViewUtils {
private static final String TAG = "ViewUtils";
public static void dumpViewHierarchy(ViewGroup root) {
final Set<String> visitedResNames = new HashSet<>();
walkNode(root, root.getResources(), visitedResNames);
}
private static void walkNode(ViewGroup node, Resources resources, Set<String> visitedResNames) {
final String resName = getResourceName(node.getId(), resources);
Log.d(TAG, "Type: " + node.getClass().getSimpleName() + "\t\tRes ID: " + resName);
if (isDuplicate(resName, visitedResNames)) {
Log.w(TAG, "Res ID: " + resName + " is duplicate");
}
final int childCount = node.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = node.getChildAt(i);
if (child instanceof ViewGroup) {
walkNode((ViewGroup) child, resources, visitedResNames);
} else {
final String childResName = getResourceName(child.getId(), resources);
Log.d(TAG, "Type: " + child.getClass().getSimpleName() + "\t\tRes ID: " + childResName);
if (isDuplicate(resName, visitedResNames)) {
isDuplicate(childResName, visitedResNames);
}
}
}
}
private static String getResourceName(int resId, Resources res) {
try {
return res.getResourceEntryName(resId);
} catch (Resources.NotFoundException e) {
return "";
}
}
private static boolean isDuplicate(String resName, Set<String> resources) {
return !TextUtils.isEmpty(resName) && !resources.add(resName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment