I'm writing a lint check to flag code that is calling a specific function from within a click listener on an Android view.
For example:
// case 1
button.setOnClickListener(object: View.OnClickListener {
override fun onClick(v: View?) {
myTestFunction()
}
})
// case 2
button.setOnClickListener {
myTestFunction()
}
// case 3
fun someOtherFunction() {
myTestFunction()
}
I would like to flag the use of myTestFunction
in both cases 1 and 2 above, but not case 3.
It's easy enough to catch all instances of myTestFunction
being called, but I'm not sure how to exclude instances that are not wrapped by a click listener. Here's what I have so far:
override fun getApplicableMethodNames(): List<String> {
return listOf("myTestFunction")
}
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
super.visitMethodCall(context, node, method)
if (method.containingClass?.qualifiedName == "com.extensions.testFunctionExtKt") {
context.report(
ISSUE, context.getCallLocation(
call = node,
includeReceiver = false,
includeArguments = false
), MESSAGE
)
}
}
I would like to add a clause to my existing if statement that matches the following pseudocode:
if (method.containingClass?.qualifiedName == "com.extensions.testFunctionExtKt"
&& "myTestFunction is being called from within a View.OnClickListener") {
// ...
}