CrazyHorse CrazyHorse - 1 year ago 103
Android Question

setOnKeyListener not responding

I am new to Android and working through a to do list example from a book. I have one Activity which is displaying an EditText and a ListView beneath it. There is an onKey event which should add the text from the EditText to the ListView and clear the EditText. However, when I hit Enter on the keyboard all that happens is a new line is added to the EditText and nothing is added to the ListView.

The onCreate code is:

protected void onCreate(Bundle savedInstanceState) {

// Get UI references
ListView myListView = (ListView)findViewById(;
final EditText myEditText = (EditText)findViewById(;
// Create ArrayList to store To Do items
final ArrayList<String> toDoItems = new ArrayList<String>();

// Create ArrayAdapter to bind items to List View
final ArrayAdapter<String> aa;

aa = new ArrayAdapter<String>(this,

// Bind Adapter to List View

myEditText.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER) ||
(keyCode == KeyEvent.KEYCODE_ENTER)) {
toDoItems.add(0, myEditText.getText().toString());
return true;
return false;

I've added the
just to ensure the reference to myEditText is working, which it is. I've tried removing the if statements from the onKey event and it just doesn't appear to be registering key events at all. Can anyone advise what I'm doing wrong here?

Answer Source

You could try using a OnEditorActionListener instead:

You could set on the edittext in XML:


and then in code:

 myEditText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
           // your action here
           return true;
      return false;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download