Could not find custom method in androidx.appcompat.widget.TintContextWrapper for onClick handler in MaterialButton

Viewed 1055

I have recently ported my app to material design and I have started to receive weird errors suggesting that methods are not found in activity (while they are and where there for last 3 years or so) and everything ends in crash for user. This seems to happen only to users that are running Android 4.* (4.0.2, 4.2, 4.4), various devices (Samsung and LG), any suggestions how to address it are appreciated! :)

Full error message:

Fatal Exception: java.lang.IllegalStateException Could not find a method onCancelClicked(View) in the activity class androidx.appcompat.widget.TintContextWrapper for onClick handler on view class com.google.android.material.button.MaterialButton with id 'btnCancel'

(...)

Caused by java.lang.NoSuchMethodException onCancelClicked [class android.view.View]

parts in italic are custom methods, see below for the layout

    <com.google.android.material.button.MaterialButton
        style="@style/Widget.MaterialComponents.Button.TextButton"
        android:id="@+id/btnCancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:onClick="onCancelClicked"
        android:text="@string/dialog_conf_code_cancel" />

Activity handling this layout implements AppCompatActivity, while the onCancelClicked is simple, as below:

public void onCancelClicked(View v) {
    this.finish();
}

I also get similar errors for other buttons implemented in this way, again - so far only for some users with Android 4.*.

My dependencies in build.gradle are defined as below

dependencies {
    implementation 'com.google.android.material:material:1.0.0'
    androidTestImplementation 'androidx.test:runner:1.1.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
    implementation 'com.google.android.gms:play-services-ads:16.0.0'
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.google.firebase:firebase-core:16.0.5'
    implementation 'com.crashlytics.sdk.android:crashlytics:2.9.6'
    implementation 'com.android.support:appcompat-v7:28.2.0'
    implementation 'com.android.support:design:28.2.0'
}

Again - any suggestions are appreciated! :)

1 Answers

After checking with several seemingly related links, the best course of action is to remove all android:onClick from XML layouts and attach the click listeners in Java instead.

My feeling about this is that it's not clear what combinations of Android and AndroidX cause this. So setting the listener in Java seems the best solution as it avoids the issue completely.

See also:

Related