Android android:onClick Must Reference an Existing Function
ID |
kotlin.android_onclick_exists |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Reliability |
Language |
Kotlin |
Tags |
android, best-practice, reliability |
Description
Reports Android layout XML elements that declare android:onClick="methodName" when no Kotlin function named methodName is defined anywhere in the scanned project.
Rationale
At runtime, the framework resolves android:onClick values by reflection against the containing Activity. If the named function does not exist, the first tap that triggers the handler raises IllegalStateException: Could not find method X in a parent or ancestor Context. The bug is invisible at compile time — the XML and Kotlin sources do not share type-level bindings — so the failure only surfaces during manual testing or in the field.
<!-- layout/activity_main.xml -->
<Button
android:id="@+id/login"
android:onClick="handleLogin" /> <!-- handleLogin() must exist in the Activity -->
// MainActivity.kt — missing the expected handler
class MainActivity : Activity() {
// no handleLogin(view: View) defined => runtime crash on first click
}