Learn Python


Click to Learn Python3

Tuesday, March 29, 2011

Example code for OnKeyDown listener in Android

In this example Toast is shown for the key presses.



The approach is simple, just we need to put this code, thats all


Java

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
super.onKeyDown(keyCode, event);
switch(keyCode)
{
case KeyEvent.KEYCODE_CAMERA:
Toast.makeText(KeyActions.this, "Pressed Camera Button", Toast.LENGTH_SHORT).show();
return true;
case KeyEvent.KEYCODE_1:
Toast.makeText(KeyActions.this, "Pressed 1", Toast.LENGTH_SHORT).show();
return true;
case KeyEvent.KEYCODE_HOME:
Toast.makeText(KeyActions.this, "Pressed Home Button", Toast.LENGTH_SHORT).show();
return true;

case KeyEvent.KEYCODE_BACK:
Toast.makeText(KeyActions.this, "Pressed Back Button", Toast.LENGTH_SHORT).show();
Intent result = new Intent("Complete");
setResult(Activity.RESULT_OK, result);
finish();
return true;
}

return false;
}


For every key there is the code, after entering the KeyEvent. the eclipse will show the list of codes available.

If you have doubts means

The full source code

Download source


Have a good day.

2 comments:

  1. numbers and other keys can be detected, but how would you detect alphabets?

    ReplyDelete
  2. Source code downloading link is not working. Anyone can give me the source code of this project?

    ReplyDelete