Beware setOnKeyListener simulating two instance which mean it pressed twice in Android


SetOnKeyListener is used when we want to track user press something in soft-keyboard. In this example, we want to track user when pressing Done key. Here are the codes :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
final EditText search = (EditText) this.findViewById(R.id.searchbox);

// Track Done key pressed
search.setOnKeyListener(new OnKeyListener() {  
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            Log.v("MYAPP", "keypressed Done!");        
            return true;
        }
       
        return false;                  
    }
});

BEWARE about this codes. We only track user for KeyEvent Enter only. We shouldn’t forget about ACTION here. When you run this code, you will see in the Log that key DONE pressed twice! Yes it should print twice!

To avoid this problem, we should pick which one ACTION will used. There are two ACTION here : UP and DOWN. In this example, I will use DOWN ACTION.

Here are the code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
final EditText search = (EditText) this.findViewById(R.id.searchbox);

// Track Done key pressed
search.setOnKeyListener(new OnKeyListener() {  
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() != KeyEvent.ACTION_DOWN) {
            Log.v("MYAPP", "keypressed Done!");        
            return true;
        }
       
        return false;                  
    }
});

When you run this code, you see only one key pressed. Problem solved! 🙂


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.