简体   繁体   中英

Java, Android passing params to method

I'm working through the android developer tutorial and we're now creating a method to match to the method name we gave to android:onClick="sendMessage" .

Here's the method:

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    // Do something in response to button
}

The text says this about the method:

In order for the system to match this method to the method name given to android:onClick, the signature must be exactly as shown. Specifically, the method must:

  • Be public
  • Have a void return value
  • Have a View as the only parameter (this will be the View that was clicked)

I understand why it must be public and why the return value is void, but why does the method take (View view) instead of just (view)? I'm coming from a Ruby background so the syntax is confusing me. Why do we pass parameters like this?

why does the method take (View view) instead of just (view)?

View表示它是一个classview只是一个variable加上这2个variable使view variable成为可以调用其所有方法的View class的对象。

This is due to the fact that onClick() method in the OnClickListener Interface which requires a parameter of type View . When you remove the parameter, Android will still attempt to call method sendMessage(View view) but that method does not exist any more, therefore you get error and app will force close.

Parameter view is the actual View (Button in your case) that was clicked. With this, you can assign multiple buttons to invoke the same method and inside the method check which button was clicked.

For more information, see this LINK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM