Android EditText Example

This tutorial shows you on how to create a EditText in XML file, and demonstrate the use of key listener to display message typed in the EditText
How it works?
1. Open “res/layout/main.xml” file, add a “EditText” component.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:gravity="center" />


2. EditText Listener
  • Attach a key listener inside your activity “onCreate()” method, to monitor following events : 
  • If “enter” is pressed , display a message box with the message typed in the “EditText” box. 
  • If “Number 9″ is pressed, display a message box with message “Number 9 is pressed!”.
package ess.edittext.isourcecode;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

public class ESSEditTextActivity extends Activity {
    /** Called when the activity is first created. */
    EditText etText;
    public void onCreate(Bundle savedInstanceState) {
        etText=(EditText) findViewById(;
        etText.setOnKeyListener(new View.OnKeyListener() {
                  public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // TODO Auto-generated method stub
                              AlertDialog.Builder b = new AlertDialog.Builder(ESSEditTextActivity.this);
                              b.setTitle("iSourcecode EditText");
                              b.setPositiveButton("OK"new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                          // TODO Auto-generated method stub
                              return true;
                        return false;
3. Run the apps (Screenshot)

Programming Language: Java + XML
Programming IDE: Eclipse