Skip to content Skip to sidebar Skip to footer

Convert A List Of KeyEvent Objects To A String

I am working on an app which needs to be able to use external USB or Bluetooth keyboard wedges. I then capture the KeyEvents and cache them as needed (starting/end sentinels). So a

Solution 1:

After much research, this is what I came up with. I used a KeyListener which accepts key events. It then appends to an Editable based on the key events (considers shifts, etc). The code below will simply echo the growing String as the key events come in.

KeyListener tkl = new TextKeyListener(Capitalize.NONE, false);
Editable et = Editable.Factory.getInstance().newEditable("");

View.OnKeyListener key = new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
            tkl.onKeyDown(null, et, keyCode, event);
        else if (event.getAction() == KeyEvent.ACTION_UP)
            tkl.onKeyUp(null, et, keyCode, event);
        else
            tkl.onKeyOther(null, et, event); //NOTE: My devices never used KeyEvent.ACTION_MULTIPLE so I don't know if it should get fired here or with the key down event.

        Log.i(("Test: " + et.toString());
    }
};

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    if (key.onKey(null, event.getKeyCode(), event))
        return true;
    else
        return super.dispatchKeyEvent(event);
}

Solution 2:

How about using getDisplayLabel() for every event? Something like:

List<KeyEvent> events = new ArrayList<KeyEvent>();
StringBuilder strEvents = new StringBuilder();
for (KeyEvent k : events) {
    strEvents.append(k.getDisplayLabel())
    strEvents.append(",");
}

String eventString = etrEvents.toString();

Solution 3:

Building on vaimvolk loop only using getUnicodeChar() ? http://developer.android.com/reference/android/view/KeyEvent.html#getUnicodeChar()


Post a Comment for "Convert A List Of KeyEvent Objects To A String"