androidkotlinandroid-softkeyboardcustom-keyboard

How to implement key preview popup in custom android keyboard


I'm currently developing a custom andriod keyboard

Sample Image:

my custom keyboard sample image

The basic structure of my keyboard is based on Microsoft SwiftKey.

I have pretty much finished everything except that I cannot find a way to implement the key preview popup.

For example (Gboard and Microsoft SwiftKey ):

Gboard sample image Microsoft SwiftKey sample image

I have looked at different posts on this implementation but all of them were like at least 5 years old and they were using the KeyboardView class, which is now deprecated and I have not used it to create my keyboard. So I tried to implement it by myself.

At first I tried to implement it like Microsoft SwiftKey, and I tried increasing the Button height each time when I pressed it but it also increased other Buttons' heights because they are in the same LinearLayout and I have used weight to set their height.

So instead I tried to implement it like Gboard but I can't quite figure out how to show the image or text above the key that the user have pressed. I tried using ImageView to show the key preview but I'm not sure how or where to add the view in the layout.

Any help or adivce would be apprecited.


Solution

  • I found out the solution by myself. Use PopupWindow: https://developer.android.com/reference/kotlin/android/widget/PopupWindow

    Create a PopupWindow and set its contentView with a TextView. Then whenever you want to show it call showAtLocation and update method.

    For example:

    val btn = Button(baseContext)
    val popup = PopupWindow()
    popup.contentView = TextView(baseContext)
    val loc = IntArray(2)
    btn.getLocationInWindow(loc)
    popup.showAtLocation(btn, Gravity.NO_GRAVITY, 0, 0)
    popup.update(loc[0], loc[1]-128, 128, 128, false)