After completing the previous lesson, you have an android application that shows an activity with a text field and a button. In this lesson, you’ll add some code to MainActivity
that show a Toast Message when the user clicks the Submit button.
Respond to the Submit Button
- In the
directory, open thejava/akraj.snow.test
MainActivity.java
file. - Within the
MainActivity
class, add the<EditText>
and<Button>
method, usefindViewById()
to get theEditText
andButton
element.EditText editText = (EditText)findViewById(R.id.edit_message); Button button = (Button)findViewById(R.id.button);
- You may use
OnClickListener
to get results, when the user clicks on the Submit button.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } });
- Get the text from
<EditText>
element, use thegetText()
method inString
variable.String text = editText.getText().toString();
- Add
Toast
method to showEditText
value to Toast Message.Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
In Android Studio, press Alt + Enter (option + return on Mac) to import missing classes.
Complete Code
package akraj.snow.test;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText editText;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
editText = (EditText) findViewById(R.id.edit_message);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String text = editText.getText().toString();
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
}
}