Android Button Illegalstateexception With Onclick(mainactivity)
Solution 1:
Why is this?
Because android:onClick="onClick"
is correct syntax. None of the following are correct syntax:
android:onClick="onClick (MainActivity)"
android:onClick="onClick (View)"
android:onClick="onClick(View)"
android:onClick="onClick and anything else"
Quoting the documentation for android:onClick
:
Name of the method in this View's context to invoke when the view is clicked. This name must correspond to a public method that takes exactly one parameter of type View. For instance, if you specify android:onClick="sayHello", you must declare a public void sayHello(View v) method of your context (typically, your Activity).
OK, with the help of @HappyRavi on Twitter, I was able to reproduce the problem. It's an IDE bug that you will encounter if you do things in a certain order:
- Add the method that you want to route the click event to
- Drag the
Button
into the GUI editor - Click the
onClick
drop-down in the Properties pane of the GUI editor
Doing things in a different order will not reproduce the problem.
With luck, they can get this fixed in some patch release for Android Studio 2.3.
Solution 2:
It should be implemented like below
<Button
android:text="Accept"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="84dp"
android:id="@+id/button2"
android:onClick="buttonClickHandler" />//name of method should be given here
And add the method in Activity file
publicvoidbuttonClickHandler(View view) {
//handle button click here
}
This will work only when method is added in Activity
class and not with Fragment
Post a Comment for "Android Button Illegalstateexception With Onclick(mainactivity)"