[英]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"
. 我正在研究android开发人员教程 ,现在正在创建一个方法,以匹配我们给
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. 为了使系统将此方法与android:onClick给出的方法名称匹配,签名必须完全如图所示。 Specifically, the method must:
具体来说,该方法必须:
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)? 我知道为什么它必须是公共的,为什么返回值是空的,但是为什么该方法采用(View view)而不是(view)? I'm coming from a Ruby background so the syntax is confusing me.
我来自Ruby背景,因此语法令人困惑。 Why do we pass parameters like this?
为什么我们要传递这样的参数?
why does the method take (View view) instead of just (view)?
View
表示它是一个class
而view
只是一个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
. 这是由于以下事实:
OnClickListener
接口中的onClick()
方法需要一个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. 当您删除参数时,Android仍将尝试调用
sendMessage(View view)
方法,但该方法已不存在,因此会出现错误,应用将强制关闭。
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.
这样,您可以分配多个按钮来调用同一方法,并在方法内部检查单击了哪个按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.