Search code examples
javaandroidkeyboardicons

Programmatically set Keyboard.Key icon


I'm using Android's Keyboard and KeyboardView classes to make a custom keyboard for an EditText (using this tutorial).

In my keyboard.xml file, I've set an icon for my shift key. However, I have another icon to display when shift is activated. However, I can't find a method that allows me to do this.


Solution

  • Instead of a setter method, there is a public icon field in the Keyboard.Key class. Simply reassign the value of this field to change a key's icon.

    Keyboard.Key key = findKey(myKeyboard, keyCode);
    key.icon = myDrawable;
    
    private Keyboard.Key findKey(Keyboard keyboard, int primaryCode) {
      for (Keyboard.Key key : keyboard.getKeys()) {
        if (key.codes[0] == primaryCode) {
          return key;
        }
      }
      return null;
    }