Install a Key Listener into an EditText

An EditText is a single-line text field. Our EditText is this color because of the colorAccent in styles.xml and colors.xml.

Tap the EditText and a software keyboard will slide up. Then type a sentence into the EditText and press the keyboard’s Pig button. In response to each keystroke, something will call the onKey method of the View.OnKeyListener object that was plugged into the EditText. The method is called twice for each keystroke: first when the finger comes down and then when it goes up. When this method detects that the Enter key was pressed down, it will translate the word into Pig Latin and display it in a Toast. The Enter key is labelled “Pig” because of the android:imeActionLabel="Pig" attribute of the EditText.

onKey returns false to tell Android to dismiss the keyboard if necessary. If it returned true, Android would do nothing and the keyboard would remain on the screen. Returning true would indicate that “the event had been completely consumed” by onKey and that no further action by anybody was necessary.

The first parameter of replaceAll is a regular expression. Regular expressions are described in Pattern.

Source code in EditText.zip

  1. MainActivity.java
  2. activity_main.xml. The android:hint prompts the user when the EditText is empty. The android:imeActionLabel is the label on the Enter key of the software keyboard. IME stands for input method editor.
  3. strings.xml. I added the string resources hint and actionLabel for the EditText.
  4. styles.xml
  5. colors.xml
  6. AndroidManifest.xml
  7. build.gradle (Module: app)

Documentation

  1. Single-line text fields in the Material Design spec.
  2. Text Fields in the User Interface guide.
  3. The Java class android.widget.EditText
    1. Documentation
    2. platform_frameworks_base/core/java/android/widget/EditText.java source code on GitHub

Run the app

Before running the app, make sure the emulator’s keyboard is enabled. Therwise, you’ll have to use the keyboad of your Mac or PC. Go to Android Studio and pull down
Tools → Android → AVD Manager
Select your virtual device and click on its pencil. In the Verify Configuration window, press Show Advanced Settings. Scroll down to Keyboard and uncheck Enable keyboard input. Then press Finish. Quit and relaunch the emulator.

If you’re running the Genymotion emulator, quit it. In the Applicatios folder of your app, launch the application Genymotion.app. Select your virtual device and click on its wrench. In the Configuration window that pops up, check the check box for “Use virtual keyboard for text input”. Then press OK.

Things to try

  1. Would it be simpler for onKey to use the editText variable in onCreate instead of the v argument passed to onKey? The editText in onCreate would have to be declared final.