【问题标题】:Could not find custom method in androidx.appcompat.widget.TintContextWrapper for onClick handler in MaterialButton在 androidx.appcompat.widget.TintContextWrapper 中找不到 MaterialButton 中的 onClick 处理程序的自定义方法
【发布时间】:2019-01-03 19:39:38
【问题描述】:

我最近将我的应用程序移植到 Material Design 中,并且我开始收到奇怪的错误,提示在活动中找不到方法(尽管它们存在并且在过去 3 年左右的时间里)并且一切都以用户崩溃告终。这似乎只发生在运行 Android 4.*(4.0.2、4.2、4.4)、各种设备(Samsung 和 LG)的用户身上,任何如何解决它的建议都非常感谢! :)

完整的错误信息:

致命异常:java.lang.IllegalStateException 找不到 Activity 类中的方法 onCancelClicked(View) androidx.appcompat.widget.TintContextWrapper 用于 onClick 处理程序 查看类 com.google.android.material.button.MaterialButton 与 id 'btnCancel'

(...)

由 java.lang.NoSuchMethodException onCancelClicked [class android.view.View]

斜体部分为自定义方法,布局见下文

    <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实现了AppCompatActivity,而onCancelClicked很简单,如下:

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

对于以这种方式实现的其他按钮,我也遇到了类似的错误 - 到目前为止,仅适用于 Android 4.* 的 一些 用户。

我在build.gradle 中的依赖定义如下

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'
}

再次感谢任何建议! :)

【问题讨论】:

  • 最新的支持库是28.0.0 not 28.2.0。任何更新的内容都以AndroidX 发布。 com.google.android.material 需要 AndroidX 但您依赖于旧的支持库。你启用Jetifier了吗?删除com.android.support:design,它是com.google.android.material:material 的旧版本,会报错。
  • 是的,Jetifier 已启用。我已经更新了依赖并推送了版本,让我们看看问题是否会消失。有趣的是,当我在本地对其进行测试时,一切似乎都很好。
  • 这个解决方案非常适合我:- stackoverflow.com/a/56311934/7398620

标签: android


【解决方案1】:

在检查了几个看似相关的链接之后,最好的做法是从 XML 布局中删除所有 android:onClick,并改为在 Java 中附加点击侦听器。

我对此的感觉是,尚不清楚 Android 和 AndroidX 的组合导致了这种情况。所以在 Java 中设置监听器似乎是最好的解决方案,因为它完全避免了这个问题。

另见:

【讨论】:

  • 好的,我试试这个方法,谢谢你的建议! :)。不幸的是,修复依赖关系没有帮助;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 2018-07-14
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
  • 2015-04-09
相关资源
最近更新 更多