AppCompatButton android:onClick Could not find a m

2020-06-21 04:58发布

I have this problem just on KitKat version, the rest from 16 API level to 25 works fine

the class that instantiates the layout have the method of the layout, example

<android.support.v7.widget.AppCompatButton
  android:onClick="onClick"
...
public void onClick(View v) {
  // do something
}

I know I can change this to listeners, databindings or use some library like Butterknife, but I'm interested in know why just crash on 4.X versions?

xml layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:onClick="onClick" />

    <android.support.v7.widget.AppCompatButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:onClick="onClick" />
</LinearLayout>

2条回答
Anthone
2楼-- · 2020-06-21 05:28

There is a workaround. Its tested on API 19 and worked fine

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:onClick="onClick" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="@style/appCompatButtonStyle"   // Note this
        android:text="Button"
        android:onClick="onClick" />
</LinearLayout>

And in your styles.xml

<style name="appCompatButtonStyle" parent="Widget.AppCompat.Button.Colored">
    <item name="backgroundTint">@color/colorWhite</item>
    <item name="android:textColor">@color/colorMaterialGrey</item>
</style>
查看更多
▲ chillily
3楼-- · 2020-06-21 05:32

I have found some explanation for this issue. It was filed as a bug. Here is the link to bug report. https://issuetracker.google.com/issues/37108938

In a gist, they say that the issue was fixed in API 24 and onClick is not compatible with support library. I have added a comment to the thread about kitkat issue.

查看更多
登录 后发表回答