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

  1. In the java/akraj.snow.test directory, open the MainActivity.java file.
  2. Within the MainActivity class, add the <EditText> and <Button> method, use findViewById() to get the EditText and Button element.
    EditText editText = (EditText)findViewById(R.id.edit_message);
    Button button = (Button)findViewById(R.id.button);
  3. 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) {
    
        }
    });
  4. Get the text from <EditText> element, use the getText() method in String variable.
    String text = editText.getText().toString();
  5. Add Toast method to show EditText 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();
            }
        });
    }

}

Run Your App

post4

Share This
Subscribe To Our Newsletter

Subscribe To Our Newsletter

Join our mailing list to receive the latest news and updates from our team.

You have successfully subscribed. You'll receive a confirmation email. Please follow the link in it to confirm your subscription.