0

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") {
  // ...
}
howettl
  • 12,419
  • 13
  • 56
  • 91
  • Can you not simply add a Boolean parameter to your test function and every time it is called from click listener, send the value as true? – Sarah Khan Apr 30 '21 at 23:19
  • I'd like to detect the situation in my lint check, not by changing the interface. – howettl May 03 '21 at 14:31

0 Answers0