Respond to the click event of the send button
Generally, we listen for click events in java code, but we can also associate click events directly through button properties: android:onClick
- <Button
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="@string/button_send"
- android:onClick="sendMessage"/>
The value "sendMessage" of android:onClick is the sendMessage() method in the activity that is called when the button is clicked.
打开src目录中的
MainActivity
文件,在类中添加如下方法:
- /** Called when the user clicks the Send button */
- publicvoid sendMessage(View view){
- // Do something in response to button
- }
Since there is a View class in the parameter of the method, you need to import the corresponding package
- import android.view.View;
In order for the system to automatically call the sendMessage method when the button is clicked, your method must adhere to the following conventions:
1. Must be a public method;
2. Must be a void return type;
3. Must have a View parameter (representing which View is clicked);