Logo Icon Logo
A Crowd-sourced Cookbook on Writing Great Android® Apps
GitHub logo Twitter logo OReilly Book Cover Art

Processing Key-Press Events in an Activity

Author: Rachee Singh -- Published? true -- FormatLanguage: W

Problem:

Intercepting the keys pressed by the user and performing actions corresponding to them.

Solution:

This can be achieved by overriding the onKeyDown method in an Activity.

Discussion:

If the application requires to react differently at different key presses, then in the Activity's Java code, the onKeyDown method needs to be overridden. This method takes the KeyCode as an argument, so within a switch-case block different actions can be carried out.


public boolean onKeyDown(int keyCode, KeyEvent service) {
	switch(keyCode) {
		case KeyEvent.KEYCODE_HOME:
			keyType.setText("Home Key Pressed!");
			break;
		case KeyEvent.KEYCODE_DPAD_CENTER :
			keyType.setText("Center Key Pressed!");
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN :
			keyType.setText("Down Key Pressed!");
			break;
		//and so on..
	}
}

Download:

The source code for this project can be downloaded from https://docs.google.com/leaf?id=0B_rESQKgad5LMDdhMDllYmYtOWE5Mi00MDU0LWE4YWEtODkwNGYwMWVkOTNl&hl=en_US.
No records found.