How to solve error: Could not find method onClick(View) in a parent or ancestor Context for android:onClick

后端 未结 5 1230
太阳男子
太阳男子 2020-12-20 19:27

I have seen that there\'s been some similar questions but the answers to those haven\'t helped me so far. The full error:

java.lang.IllegalStateExcept

相关标签:
5条回答
  • 2020-12-20 19:37

    You need to change android.support.v7.widget.AppCompatButton

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <android.support.v7.widget.AppCompatButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Random Game"
            android:id="@+id/button_random"
            android:layout_gravity="center_horizontal"
            android:onClick="onClick" />
    </LinearLayout>
    
    0 讨论(0)
  • 2020-12-20 19:43

    I had the same issue, in my case I have 2 activities using the same layout so when I changed the OnClick event name it will crash in other activity try to check the setContentView layout in the crashing activity

    0 讨论(0)
  • 2020-12-20 19:50

    Please rename onClick method to anything other than that, Android thinks you are calling the internal onClick from View.java exposed via OnClickListener interface

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Random Game"
        android:id="@+id/button_random"
        android:layout_gravity="center_horizontal"
        android:onClick="myOnClick" />
    

    and in your Activity

    public class StartActivity extends AppCompatActivity {
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_start);
            }
    
            public void myOnClick(View v) {
              Log.d("DEBUG", "CLICKED " + v.getId());
            }
    }
    

    You can check the View documentation here

    0 讨论(0)
  • 2020-12-20 19:57

    I had the same problem and in my case, I changed Button in XML to android.support.v7.widget.AppCompatButton and it worked.

    Code with Error:

     <Button
            .... />
    

    Fixed Code:

     <android.support.v7.widget.AppCompatButton
            .... />
    
    0 讨论(0)
  • 2020-12-20 19:57

    In my case I missed closing bracket at the end.

    android:onClick="@{(v) -> CommentHandler.selectGallery(v)".

    It should be like this.
            android:onClick="@{(v) -> CommentHandler.selectGallery(v)}".
    
    0 讨论(0)
提交回复
热议问题