I am using the android's custom keyboard to build a keypad. The OnKeyboardActionListener in android returns the "keyCode" of the key being pressed. But I want in particular, the onscreen x and y coordinates of that key ( with or without using the keyCode ).
P.S : Even coordinates of the center of the key would help. I have found a method "squaredDistanceFrom" which returns the squared distance between the center of the key and point where the screen is touched. Is there a function which returns the center's coordinates?
I know this question is quite old now, but I have been working on a project over the past two weeks with similar requirements and I struggled finding a solution. So here is what I propose:
Build a working keyboard
First, let start from a functional keyboard. Some very useful resources to get started:
Get the coordinates of the key pressed
I haven't found a direct way of retrieving the coordinates from the key pressed in the API.
However, we can determine and retrieve the actual instance the key pressed. First we need to create an
onTouchListener
on the KeyboardView. This will allow us to retrieve aMotionEvent
and consequently the coordinates of the touch event within the view.Then, there is a method in the
Keyboard
class which is calledgetKeys
returning a list ofKeys
. We can then use theisInside
method from theKey
class to verify that the coordinates retrieved previously are inside of the key or not, and thereby retrieving the instance of the key pressed.We need to retrieve the list of keys from the current keyboard every time is is displayed. This way, even if the user swaps from one layout to another (by using symbols or numbers for instance), we get the correct set of keys. We can do so by overriding the
onStartInputView
method from our class.Sample
Retrieve the keys:
Override the onStartInputView which is called when the keyboard is displayed:
Create an onTouchListener for the KeyboardView:
Entire example (without the package and imports):
Note: Tested on a Motorola Moto G XT1039 Android 5.1 API 22