自定义 lint 规则:如何修复“此注释不适用于目标‘表达式’”

问题描述 投票:0回答:1

我正在为 android/compose 编写我的第一个自定义 lint 检测器:

“不要使用标准按钮,使用我们专门设计的自定义按钮”


探测器本身按预期工作:


Lint 抑制无法按预期工作:“此注释不适用于目标‘表达式’”


我必须恢复到不同的范围才能使其正常工作:


我怎样才能以这样的方式修复我的 lint 规则,以便我可以定位表达式?


我当前(简化)的实现:

class MissingDefaultDetector : Detector(), SourceCodeScanner {

    companion object {
        private const val old = "Button"

        @JvmField
        val ISSUE: Issue = Issue.create(
            id = "PreferDefaultComposables",
            briefDescription = "Prefer 'DefaultComposables'",
            explanation = "The default implementation should be used",
            category = Category.CORRECTNESS,
            priority = 6,
            severity = Severity.WARNING,
            implementation = Implementation(
                MissingDefaultDetector::class.java,
                Scope.JAVA_FILE_SCOPE
            )
        )
    }

    override fun getApplicableMethodNames(): List<String> = listOf(old)

    override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
        context.report(
            issue = ISSUE,
            scope = node,
            location = context.getNameLocation(node),
            message = "Prefer our custom version(s) of this component",
        )
    }
}
android static-analysis android-lint
1个回答
0
投票

错误消息“此注解不适用于目标‘表达式’”表示 @SuppressLint("PreferDefaultComposables") 注解不能用在表达式上,只能用在声明上(例如类、字段、方法或参数) ).

在您的代码中,@SuppressLint("PreferDefaultComposables") 注释用于 Button 函数调用。这是不允许的,因为函数调用是一个表达式,而不是声明。

要解决此问题,有两种方法

方法 1 -

@Composable
fun ButtonText() {

    // Declare the Button function call inside a lambda expression
    @SuppressLint("PreferDefaultComposables")
    val button: Unit = Button(onClick = { }) {
        Text(text = "Click me")
    }
}

方法2

@Composable
fun ButtonText() {

    @SuppressLint("PreferDefaultComposables")
    @Composable
    fun InnerButton() {
        Button(onClick = { }) {
            Text(text = "Click me")
        }
    }

    InnerButton()
}

默认的方法是在外部或 onButtonText 函数中声明。但你需要的是在里面声明。希望这些方法对你有帮助

© www.soinside.com 2019 - 2024. All rights reserved.