我最近将我的应用程序移植到 Material Design,我开始收到奇怪的错误,提示在 Activity 中找不到方法(虽然它们在过去 3 年左右的时间里存在)并且一切都以用户崩溃告终。这似乎只发生在运行 Android 4.*(4.0.2、4.2、4.4)、各种设备(三星和 LG)的用户身上,如有任何解决方法的建议,我们将不胜感激! :)
完整错误信息:
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]
斜体部分为自定义方法,布局见下
<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'
}
再一次 - 任何建议表示赞赏! :)
最佳答案
在检查了几个看似相关的链接后,最好的做法是从 XML 布局中删除所有 android:onClick
并改为在 Java 中附加点击监听器。
我对此的感觉是,尚不清楚 Android 和 AndroidX 的哪些组合会导致此问题。所以在 Java 中设置监听器似乎是最好的解决方案,因为它完全避免了这个问题。
另见:
关于android - 无法在 androidx.appcompat.widget.TintContextWrapper 中为 MaterialButton 中的 onClick 处理程序找到自定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54028752/