如何实现 LintFix 以将缺少的注释添加到 Android 中的类定义中

Hec*_*tor 2 android lint

我正在调查我当前的 Android 应用程序中的自定义 Lint 规则开发。

我的检测器找到我的项目中未使用特定注释进行注释的所有活动。

我想创建一个 LintFix,添加缺少的注释,如下所示:-

活动出错

class MyActivity : AppCompatActivity() {
...
}
Run Code Online (Sandbox Code Playgroud)

活动固定

@MyMissingAnnotation
class MyActivity : AppCompatActivity() {
...
}
Run Code Online (Sandbox Code Playgroud)

我开发的代码是:-

        val fix = LintFix.create()
            .replace()
            .text("")
            .with("@MyMissingAnnotation")
            .build()
Run Code Online (Sandbox Code Playgroud)

然而这会导致以下损坏的代码

class @MyMissingAnnotationMyActivity : AppCompatActivity() {
...
}
Run Code Online (Sandbox Code Playgroud)

因为我的报告类似于这样

 context.report(
         ISSUE, node,
         context.getNameLocation(node),
         "Activities require the @MyMissingAnnotation annotation.",
          fix
  )
Run Code Online (Sandbox Code Playgroud)

如何在班级的正确位置添加所需的注释?

Lon*_*ger 5

您可以使用shortenNames(),beginning()reformat(true)来使您的修复更加合理

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