Edit Text

PDF for offline use
Sample Code:

Let us know how you feel about this

Translation Quality


0/250

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.

  • 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"/>
  • 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 Handled property 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).

    • 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 .

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.