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.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button_random'
The 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());
}
}
The 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 have added the activity to the AndroidManifest.xml. I have similar activities that work in the same way and I don't have any problems with those...
Does anyone see something where I am missing something or have made a mistake?
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)}".
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With