Edit Text

A text field for user input. We'll make it display the text entered so far when the "Enter" key is pressed.

1. Open the layout file and, inside the LinearLayout, add the EditText element:

<EditText android:id="@+id/edittext" android:layout width="fill parent" android:layout height="wrap content"/>

2. To do something with the text that the user enters, add the following code to the end of the onCreate() method:

final EditText edittext = (EditText) findViewById(R.id.edittext);

edittext.setOnKeyListener(new OnKeyListener() {

public boolean onKey(View v, int keyCode, KeyEvent event) {

if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)) {

// Perform action on key press

Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();

return true;

return false;

This captures our EditText element from the layout, then adds an on-key listener to it. The View.OnKeyListener must define the onKey() method, which defines the action to be made when a key is pressed. In this case, we want to listen for the Enter key (when pressed down), then pop up a Toast message with the text from the EditText field. Be sure to return true after the event is handled, so that the event doesn't bubble-up and get handled by the View (which would result in a carriage return in the text field). 3. Run it.

0 0

Post a comment