Pages

Sunday, December 07, 2025

Android Log View Hierarchy

While I was trying to implement (or rather suppoer) Dark/Light mode in one of my android apps, I needed to debug the view hierarchy , and the Layout Inspector in Android Studio only gives you the view id  names, like R.id.xxxx, but not the numeric value.

So I created this fine log function for the view hierarchy - notice the recursion for view groups ;)
private void logViewHierarchy(@NonNull View view, int depth)
{
String indent = " ".repeat(depth);

String resourceId;
int id = view.getId();
if (id != View.NO_ID) {
try {
resourceId = getResources().getResourceEntryName(id);
} catch (Exception e) {
// Handles case where ID might be dynamic or not found in resources
resourceId = String.valueOf(id);
}
} else {
resourceId = "NO_ID";
}

String simpleName = view.getClass().getSimpleName();
Log.d(TAG, "%s[%s] ID: %s = 0x%08x".formatted(indent, simpleName, resourceId, id));

if (view instanceof ViewGroup viewGroup)
{
for (int i = 0; i < viewGroup.getChildCount(); i++) {
View child = viewGroup.getChildAt(i);
logViewHierarchy(child, depth + 1); // Increase indent depth for children
}
}
}
When I then added this at the end of the onCreate() in my Activity, it (or course??) did not show any of the childer of the main RecyclerView I was using, so let's do it, once layouting is done.
Best with this little trick:
binding.recyclerview.getViewTreeObserver().
   addOnGlobalLayoutListener(() -> logViewHierarchy(binding.getRoot(), 0));
In essence, you register an observer for when the layout for the RecyclerView is done, and blog then (notice the lamdba there calling my log function). 

Et voilà - full recycler being logged.

No comments:

Post a Comment