In Android, you can use “EditText” class to create an editable textbox to accept user input.

This tutorial show you how to create a textbox in XML file, and demonstrates the use of key listener to display message typed in the textbox.

P.S This project is developed in Eclipse, and tested with Android 2.3.3.

1. EditText

Open “res/layout/main.xml” file, add a “EditText” component.

File : res/layout/main.xml

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

        android:layout_height="wrap_content" >

        <requestFocus />



2. EditText Listener

Attach a key listener inside your activity “onCreate()” method, to monitor following events :

  1. If “enter” is pressed , display a floating box with the message typed in the “EditText” box.
  2. If “Number 9” is pressed, display a floating box with message “Number 9 is pressed!”.

File :


import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

 private EditText edittext;

 public void onCreate(Bundle savedInstanceState) {


 public void addKeyListener() {

	// get edittext component
	edittext = (EditText) findViewById(;

	// add a keylistener to keep track user input
	edittext.setOnKeyListener(new OnKeyListener() {
	public boolean onKey(View v, int keyCode, KeyEvent event) {

		// if keydown and "enter" is pressed
		if ((event.getAction() == KeyEvent.ACTION_DOWN)
			&& (keyCode == KeyEvent.KEYCODE_ENTER)) {

			// display a floating message
				edittext.getText(), Toast.LENGTH_LONG).show();
			return true;
		} else if ((event.getAction() == KeyEvent.ACTION_DOWN)
			&& (keyCode == KeyEvent.KEYCODE_9)) {

			// display a floating message
				"Number 9 is pressed!", Toast.LENGTH_LONG).show();
			return true;

		return false;

3. Demo

Run the application.

1. Type something inside the textbox, and press on the “enter” key :

android textbox demo1

2. If key “Number 9” is pressed :

android textbox demo2

Download Source Code

Download it – (15 KB)


  1. Android EditText JavaDoc
  2. Android EditText example