Yossi Yossi - 3 months ago 37
Android Question

print a view hierarchy on a device

Debugging my app with strange results on Samsung phones, which I don't have physical access to. I'd like to ask a user to run an instrumented App to help debug. My App gets a view that has an unknown (to me ;-) hierarchy in it (ViewGroups etc). Is there a way to "walk" a View and print out to a string / ddms all the components in the View (etc ViewGroups in it etc)?

This would be akin to HierarchyViewer tool - if I had adb level access to the device.

Update: I guess I could use the method

void dumpViewHierarchyWithProperties(Context context, ViewGroup group, BufferedWriter out, int level)

from the ViewDebug.java Android OS sources ...

Anyone have a better idea?



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);