Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the View class object as a parameter to the method invoked by a button (View view)

Tags:

java

android

xml

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

like image 427
willsantoso Avatar asked Dec 20 '12 11:12

willsantoso


People also ask

How to implement OnClick method in android?

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.

Why is the datatype of the input parameter declared as view?

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.

Which callback is called when a button is tapped?

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.


1 Answers

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.

like image 177
ben75 Avatar answered Oct 19 '22 23:10

ben75