Cross Platform
Android
iOS
Mac

Edit Text

In this section, you will create a text field for user input, using the EditText widget. Once text has been entered into the field, the "Enter" key will display the text in a toast message.

  1. Open the Resources\layout\main.xml file and add the EditText element (inside the LinearLayout):
    <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 types, add the following code to the end of the OnCreate() method:
    EditText edittext = FindViewById<EditText>(Resource.Id.edittext);
    
    edittext.KeyPress += (object sender, View.KeyEventArgs e) => {
            e.Handled = false;
            if (e.Event.Action == KeyEventActions.Down && e.KeyCode == Keycode.Enter) {
                    Toast.MakeText (this, edittext.Text, ToastLength.Short).Show ();
                    e.Handled = true;
            }
    };
    

    This captures the EditText element from the layout and sets a KeyPress handler, which defines the action to be made when a key is pressed while the widget has focus. In this case, the method is defined to listen for the Enter key (when pressed down), then pop up a Toast message with the text that has been entered. The ReturnValue should always be true if the event has been handled, so that the event doesn't bubble-up (which would result in a carriage return in the text field).

  3. Run the application.

Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License. This tutorial is based on the Android Form Stuff tutorial.