package

androidx.resourceinspection

Overview

Android Studio ships a Layout Inspector tool that enables developers to examine their Views or Compose based UI while it's running on a device. It works by using JVMTI over ADB to inject code into a debuggable application which collects information about the view hierarchy and screen captures and pipes them back to Studio.

Getting this working in a library with custom views takes some work to connect all the dots for the inspector:

  1. Views with custom attributes need to call in their constructor. This adds custom attributes to the attribute resolution stack. The inspector consumes this information to show developers where in XML an attribute value came from, which can help debug configuration-specific resources.
  2. Add the resource inspection annotation processor to your build and add a dependency on the annotation package. For Gradle, this is as simple as an annotationProcessor dependency. For Kotlin projects, use KAPT instead.
  3. Annotate getters for custom attributes with @Attribute. The annotation processor uses these to generate an InspectionCompanion for each view. The inspector finds these reflectively and uses them to quickly read all of the attributes of the view.
A minimal example looks something like this:
 public class CustomView extends View {
     public CustomView(
         @NonNull Context context,
         @Nullable AttributeSet attrs,
         int defStyleAttr,
         int defStyleRes
     ) {
         super(context, attrs, defStyleAttr, defStyleRes);
         TypedArray attributesArray = context.obtainStyledAttributes
             attrs, R.styleable.CustomView, defstyleAttr, defStyleRes);
         ViewCompat.saveAttributeDataForStyleable(
             this, context, R.styleable.CustomView, attrs, attributeArray,
             defStyleAttr, defStyleRes);
     }

     @Attribute("com.example:customAttribute")
     public int getCustomAttribute() { /* ... */ }
 }