If you look carefully in the XML, you'll see the following attribute on the button:
android:onClick="sendMessage"
This attribute means that when the button is clicked, message
public void sendMessage(View view)
is invoked. This is due to the fact that onClick
method in the OnClickListener
interface requires a parameter of type View
. When you remove the parameter, android still attempts to call method sendMessage(View view)
but that method does not exist any more, therefore you get a 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.
If you want to have the method without the parameters, then you should assign it in the code instead of the XML. Change your XML to be
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:id="@+id/send_button" />
(Note that android:onClick
attribute is now removed and android:id
is added.) Then in your activity in onCreate
method you would add the following line:
this.findViewById(R.id.send_button).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendMessage();
}
}
As you can see, this is quite a bit more code to write, but it does provide you with more flexibility should you need it.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…