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

I saw that there were some similar questions, but the answers to them have not yet helped me. Full error:

java.lang.IllegalStateException: Could not find onClick (View) method in parent or ancestor Context for android: onClick attribute is defined on a class of the type android.support.v7.widget.AppCompatButton with the identifier 'Button_random'

Class ( StartActivity.java ):

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

XML ( activity_start.xml ):

 <?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"> <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="onClick" /> </LinearLayout> 

I added activity to AndroidManifest.xml. I have similar actions that work the same and I have no problems with these ...

Does anyone see something where I'm missing something or made a mistake?

+5
source share
2 answers

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

Error code:

  <Button .... /> 

Fixed Code:

  <android.support.v7.widget.AppCompatButton .... /> 
+2
source

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
source

All Articles