I'm trying to create an app for Android, and I follow this tutorial http://developer.android.com/training/basics/firstapp/starting-activity.html
there is a part
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
}
then I followed this tutorial and everything worked, untill I remove parameter View view
my question is just why everytime I remove it, so the function just be:
/** Called when the user clicks the Send button */
public void sendMessage() {
// Do something in response to button
}
and I run the app, it forced close.
could anyone enlighten me? thank you
To define the click event handler for a button, add the android:onClick attribute to the <Button> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
It is there to let you reuse event handlers like the OnClick method, the View parameter is in your case the Button instance that has fired the method - multiple Buttons can have the same OnClick handler, inside the method you can check which of the Buttons has fired (if there are more than one) and react accordingly.
The callback method for the android:onClick attribute must be public , return void , and define a View as its only parameter (this is the View that was tapped). Use the method to perform a task or call other methods as a response to the Button tap.
When you put this kind of thing in your xml :
android:onClick="sendMessage"
The android framework will add an OnClickListener on your button. This "automatically" generated OnclickListener will try to call a method named "sendMessage" with one single argument of type View.
If this method doesn't exists it simply crash.
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