print a view hierarchy on a device
Here's the utility function I just made for this purpose:
public static void printViewHierarchy(ViewGroup vg, String prefix) {
for (int i = 0; i < vg.getChildCount(); i++) {
View v = vg.getChildAt(i);
String desc = prefix + " | " + "[" + i + "/" + (vg.getChildCount()-1) + "] "+ v.getClass().getSimpleName() + " " + v.getId();
Log.v("x", desc);
if (v instanceof ViewGroup) {
printViewHierarchy((ViewGroup)v, desc);
}
}
}
I've created utility method which returns hierarchy in a pretty printed way with human readable view ids. Here is an example of the output:
[LinearLayout] no_id
[CardView] com.example:id/card_view
[RelativeLayout] no_id
[LinearLayout] com.example:id/image_container
[AppCompatImageView] com.example:id/incident_icon
[CustomTextView] com.example:id/road_number
[RelativeLayout] no_id
[CustomTextView] com.example:id/distance_to_user
[CustomTextView] com.example:id/obstruction_title
[CustomTextView] com.example:id/road_direction
[CustomTextView] com.example:id/obstruction_description
[AppCompatImageView] com.example:id/security_related
Here is the utility method:
public static String getViewHierarchy(@NonNull View v) {
StringBuilder desc = new StringBuilder();
getViewHierarchy(v, desc, 0);
return desc.toString();
}
private static void getViewHierarchy(View v, StringBuilder desc, int margin) {
desc.append(getViewMessage(v, margin));
if (v instanceof ViewGroup) {
margin++;
ViewGroup vg = (ViewGroup) v;
for (int i = 0; i < vg.getChildCount(); i++) {
getViewHierarchy(vg.getChildAt(i), desc, margin);
}
}
}
private static String getViewMessage(View v, int marginOffset) {
String repeated = new String(new char[marginOffset]).replace("\0", " ");
try {
String resourceId = v.getResources() != null ? (v.getId() > 0 ? v.getResources().getResourceName(v.getId()) : "no_id") : "no_resources";
return repeated + "[" + v.getClass().getSimpleName() + "] " + resourceId + "\n";
} catch (Resources.NotFoundException e) {
return repeated + "[" + v.getClass().getSimpleName() + "] name_not_found\n";
}
}
Tip: we use this method to add view hierarchies to some crash reports. In some cases it is really helpful.