'How do you implement LintFix to add missing annotation to class definition in Android

I am investigation custom Lint Rules development in my current Android Application.

My detector finds all Activities in my project that are not annotated with a specific annotation.

I would like to create a LintFix that adds the missing annotation as follows:-

Activity in Error

class MyActivity : AppCompatActivity() {
...
}

Activity fixed

@MyMissingAnnotation
class MyActivity : AppCompatActivity() {
...
}

The code I have developed is :-

        val fix = LintFix.create()
            .replace()
            .text("")
            .with("@MyMissingAnnotation")
            .build()

however this results in the following corrupt code

class @MyMissingAnnotationMyActivity : AppCompatActivity() {
...
}

as my report resembles this

 context.report(
         ISSUE, node,
         context.getNameLocation(node),
         "Activities require the @MyMissingAnnotation annotation.",
          fix
  )

How can I add the required annotation at the correct location in my class?



Solution 1:[1]

You can use shortenNames(), beginning() and reformat(true) to make your fix more reasonable

val fix = LintFix.create()
                .replace()
                .text("")
                .with("@com.foo.bar2.MyMissingAnnotation")
                .beginning()
                .shortenNames()
                .reformat(true)
                .range(context.getLocation(node as UElement))
                .build()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Long Ranger