在 运行 时间内更改软键盘上的按键图标

Change key icon on a softkeyboard in run time

我正在尝试在 运行 时间内更改软键盘上的按键图标:

@Override
public void onPress(int primaryCode) {

    Keyboard currentKeyboard = mInputView.getKeyboard();
    List<Keyboard.Key> keys = currentKeyboard.getKeys();
    mInputView.invalidateKey(primaryCode);

    keys.get(primaryCode).label = null;
    keys.get(primaryCode).icon = ContextCompat.getDrawable(getApplicationContext(), android.R.drawable.ic_dialog_email);

}

可以,但是当我按下一个键时,改变了另一个键的图标。你知道为什么吗?

(我正在使用 API 级别 8)

这样做

@Override
public void onPress(int primaryCode) 
{
    Keyboard currentKeyboard = mInputView.getKeyboard();            
    List<Keyboard.Key> keys = currentKeyboard.getKeys();
    mInputView.invalidateKey(primaryCode);

    for(int i = 0; i < keys.size() - 1; i++ )
    {
        Keyboard.Key currentKey = keys.get(i);

        //If your Key contains more than one code, then you will have to check if the codes array contains the primary code
        if(currentKey.codes[0] == primaryCode) 
        {
            currentKey.label = null;
            currentKey.icon = getResources().getDrawable(android.R.drawable.ic_dialog_email);
            break; // leave the loop once you find your match
        }
    }
}

您的代码无法正常工作的原因: 这里的罪魁祸首是 keys.get(primaryCode)。您需要从 Keys 列表中获取 Key。因为 Listget() 方法需要您要获取的对象的位置。但是您没有传递对象的位置,而不是传递键的 unicode 值。所以,我所做的就是使用它的位置从 List 中正确地获取 Key。现在,我通过 运行 一个 for 循环并将每个 Key 的 unicode 值与当前按下的 Key 的 unicode 值进行比较来获得位置。

注意:在某些情况下,一个 Key 有多个 unicode 值。在这种情况下,您将不得不更改 if 语句,您将在其中检查代码数组是否包含 primaryCode.