Android Development #8

Respond to the Send Button

Follow these steps to add a method to the MainActivity class that’s called when the Send button is tapped:

  1. In the file app > java > com.example.myfirstapp > MainActivity, add the following sendMessage() method stub:
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {

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


You might see an error because Android Studio cannot resolve the View calss used as the method argument. To clear the error click the View declaration, place your cursor on it, and then press Alt+ Enter, or Option + Enter on a Mac, to perform a Quick Fix. If a menu appears, select Import class.

2. Return to the activity_main.xml file to call the method from the button:

  • Select the button in the Layout Editor.
  • In the Attributes window, locate the onClick property and select SendMessage [MainActivity] from its drop-down list.

Now when the button is tapped, the system calls the sendMessage() method.

Take note of the details in this method. Thet’re required for the system to recognize the method as compatible with the android:onClick attribute. Specially, the method has the following characterstics:

  • Public Access
  • A void, or in Kotlin, an implict unit return value.
  • A view as the only parameter. This is the view object you clicked at the end of Step 1.

3. Next, fill in this method to read the contents of the text field and deliver that text to another activity.

Sometimes I write, sometimes I write well…:)