Letting Android Lint fix your code

Android Lint is deeply integrated into Android Studio. Issues that are reported will be highlighted either as warnings or errors.

Lint warning about synthetic accessor methods

Since Android Studio 3.0.0 the integration has gotten even better as we can quick-fix issues by pressing Alt + Enter.

Lint telling us to make Foo#foo package private

After doing so the warning is gone.

No Lint warning anymore \o/

While that is super good there hasn’t been anything for the Terminal. Not anymore. Starting with Android Gradle Plugin 3.2.0 Lint got a lot smarter and you can simply execute the lintFix Gradle task.

It will fix all of the issues it can and break the build since changes were done after compilation. Doing a git diff yields the correct change that is required:

Quick-fix diff

Super handy. With this, you can let Lint auto perform a bunch of fixes and you don’t need to do them hand by hand.

Not every Lint rule supports this out of the box. Authors of Lint rules need to opt-in:

val import = importReference.asSourceString()
if (import.startsWith("org.assertj.core.api.Assertions")) {
val fix = LintFix.create()
.replace()
.text(import)
.with(import
.replace("org.assertj.core.api.Assertions",
"org.assertj.core.api.Java6Assertions")
)
.build()
  context.report(ISSUE_ASSERTJ_IMPORT, node,
context.getLocation(importReference),
"Should use Java6Assertions instead", fix)
}

This is an example of one of my lint rules that replaces org.assertj.core.api.Assertions imports with org.assertj.core.api.Java6Assertions. As you can see it’s pretty trivial to add quick-fix support.

If you want to learn more about writing your first custom Lint rules check out my article for more information.