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="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/txt1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text"
        android:gravity="center" />


</LinearLayout>

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.app.Activity;
import android.app.AlertDialog;
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;
      @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        etText=(EditText) findViewById(R.id.txt1);
        etText.setOnKeyListener(new View.OnKeyListener() {
                 
                  @Override
                  public boolean onKey(View v, int keyCode, KeyEvent event) {
                        // TODO Auto-generated method stub
                        if((event.getAction()==KeyEvent.ACTION_DOWN)&&(keyCode==KeyEvent.KEYCODE_ENTER)){
                              AlertDialog.Builder b = new AlertDialog.Builder(ESSEditTextActivity.this);
                              b.setTitle("iSourcecode EditText");
                              b.setMessage(etText.getText());
                              b.setPositiveButton("OK"new DialogInterface.OnClickListener() {
                                   
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                          // TODO Auto-generated method stub
                                         
                                    }
                              });
                              b.show();
                              return true;
                        }
                        return false;
                  }
            });
    }
}
3. Run the apps (Screenshot)

Programming Language: Java + XML
Programming IDE: Eclipse