I am designing a custom keyboard for Amharic language in Android, but the following is applicable to many other non-English languages.
Two or more combination of keys translate to one character. So, if the user types 'S', the keyboard will output 'ሰ'... and if they follow it with the letter 'A', the 'ሰ' is replaced with 'ሳ'.
I managed to get a solution, as below, working by looking at the character before the cursor and checking it against a Map. However, I was wondering whether there is a simpler and cleaner solution possible.
public void onKey(int primaryCode, int[] keyCodes) {
InputConnection ic = getCurrentInputConnection();
HashMap<String, Integer> en_to_am = new HashMap<String, Integer>();
CharSequence pChar = ic.getTextBeforeCursor(1, 0);
int outKey = 0;
//build a hashmap of 'existing character' + 'new key code' = 'output key code'
en_to_am.put("83", 4656);
en_to_am.put("ሰ65", 4659);
try {
//see if config exists in hashmap for 'existing character' + 'new key code'
if (en_to_am.get(pChar.toString() + primaryCode) != null) {
outKey = en_to_am.get(pChar.toString() + primaryCode);
ic.deleteSurroundingText(1, 0);
} else {
//else just translate latin to amharic (ASCII 83 = ሰ)
if (en_to_am.get("" + primaryCode) != null) {
outKey = en_to_am.get("" + primaryCode);
} else {
//if no translation exists, just output the latin code
outKey = primaryCode;
}
}
} catch (Exception e) {
outKey = primaryCode;
}
char code = (char) outKey;
ic.commitText(String.valueOf(code), 1);
}
Initialize en_to_am in static code
Skip the try.
Here are some changes I would suggest to make it more efficient
Here is the modified code