Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
326 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...