59

I have an Edit Text that is defined as follows.

<EditText  
android:layout_width="fill_parent" 
android:layout_height="wrap_content"
android:maxLines="1"
android:inputType="text" 
android:hint="@string/field_text"
android:id="@+id/field"
/>

I want to set a custom command so that when somebody clicks on the Done/Go button on the onscreen keyboard a button is clicked or just run the methods that are run by the button. I think this has something to do with ime options but I havent been able to figure out how they work. Thanks in advance for any help!

Corey Alexander
  • 905
  • 1
  • 7
  • 15

2 Answers2

141

You want a combination of android:imeOptions and setOnEditorActionListener

<EditText android:id="@+id/some_edittext"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:imeOptions="actionSend">
</EditText>


some_edittext.setOnEditorActionListener(new OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            some_button.performClick();
            return true;
        }
        return false;
    }
});

Obviously you should change actionSend to the action you want, and update IME_ACTION_SEND correspondingly.

Austyn Mahoney
  • 11,398
  • 8
  • 64
  • 85
Niall Sheridan
  • 1,536
  • 2
  • 10
  • 6
  • 1
    Just wanted to follow up on this answer and mention that this doesn't necessarily work on all devices. For example, I changed my OnKeyListener code to use OnEditorActionListener in my app and suddenly my HTC Evo stopped performing the action. See this for more info: http://stackoverflow.com/questions/3886677/imeoptions-on-htc-devices – Dan May 13 '11 at 20:32
  • But Using this example u can't create multiline editext.Like a chat text,in this u added text is not Wrodwrap automaticaly. – Zala Janaksinh Jan 01 '14 at 04:50
0

Take a look at the setImeActionLabel method (or imeActionLabel and imeActionId attributes) and setOnEditorActionListener to set a listener to respond to the events.

adamp
  • 28,862
  • 9
  • 81
  • 69