In this blog, you will implement the project for the following task: the user enters a message to the edit text then clicks the OK button. The current text Mobile Technologies will be replaced with the entered message.
1. Open MainActivity.java, add the following displayMessage method (below the onCreate method) to implement the Click event listener.
public void displayMessage(View view) {
TextView textView = findViewById(R.id.textViewOutput);
EditText editText = findViewById(R.id.editTextInput);
textView.setText(editText.getText());
}
If you see View, TextView and EditText in red colour, click on the first one, that is View, wait for a while then you will see a small pop-up window that asks you to press Alt + Enter to fix this error (this is to import missing libraries to your project). Repeat this step until you have no red text.
The first line TextView textView = findViewById(R.id.textViewOutput); is to find the TextView widget by its id then assign all its attribute values to the textView object. The second line is doing a similar task for the EditText widget. The third line textView.setText(editText.getText()); is to get text from the editText object using the getText method and assigns the text to the textView object using the setText method.
2. This is done at design time. There is another option to attach the click event listener to the button when the app is running (regarded as at runtime). Run the app. The click event listener method displayMessage gets text from inputText then sets it to textViewOutput. Now you can test it (enter a message then tap the OK button, the current Mobile Technologies text will be replaced with the input message).
3. To display a toast message at the bottom, add the following to the displayMessage method:
Toast.makeText(this,"OK button clicked.", Toast.LENGTH_LONG).show();
4. To comment out a line of code, click on that line then press Ctrl+/. Press Ctrl+/ again to uncomment that line.