Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android capture hardware keyboard event without edittext view

How can I capture the hardware keyboard events without using an EditText field?

For example, in a simple activity the display a square on the screen, when a "B" is pressed on the slide keyboard I want to turn it blue, when a "G" is presses, turn it Green, etc.

I don't need help with the color code, just how to intercept the keypress

This is not about the soft or virtual keyboard

like image 560
Noah Avatar asked Mar 14 '11 08:03

Noah


People also ask

How do I keep my keyboard visible on Android?

You must have an EditText in your layout and that need to extent EditText base class. then Override onKeyPreIme() method, and return True. Now your keyboard will be always visible and can't be dismissed by Back key. Caution: Because of your onKeyPreIme() method returns true you can't exit your app using back key.

How to Handle keyboard in Android studio?

To handle an individual key press, implement onKeyDown() or onKeyUp() as appropriate. Usually, you should use onKeyUp() if you want to be sure that you receive only one event. If the user presses and holds the button, then onKeyDown() is called multiple times.

What is the KeyDown event in Android?

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.

What is soft input mode Android?

The Android system shows an on-screen keyboard—known as a soft input method—when a text field in your UI receives focus.


1 Answers

Android classes usually provide event handlers, you can implement when subclassing them. The Activity class has the following event handlers:

  • onKeyDown(int keyCode, KeyEvent event)
  • onKeyLongPress(int keyCode, KeyEvent event)
  • onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)
  • onKeyShortcut(int keyCode, KeyEvent event)
  • onKeyUp(int keyCode, KeyEvent event)

In addition all views have the following event handlers:

  • onKeyDown(int, KeyEvent)
  • onKeyUp(int, KeyEvent)

I guess there are many other classes that have similar event handlers for key events, but this should be enough for your situation. The KeyEvent then contains information about the pressed key, i.e. the key code.

like image 138
poke Avatar answered Nov 15 '22 00:11

poke