highpass
highpass

Reputation: 163

Change key icon on a softkeyboard in run time

I'm trying to change a key icon on press on a softkeyboard in run time with:

@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);

}

It works, but when I press a key, change the icon of other key. Do U know why?

(I'm using API level 8)

Upvotes: 0

Views: 2478

Answers (1)

Rohit5k2
Rohit5k2

Reputation: 18112

Do this

@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
        }
    }
}

Reason your code is not working: The culprit here is keys.get(primaryCode). You need to get the Key from Keys list. Because get() method of a List expects the position of the object you want to fetch. But you are not passing they position of the object, rather than you are passing the unicode value of the key. So, all I did was to fetch the Key correctly from the List using its position. Now, I got the position by running a for loop and comparing each Key's unicode value with currently pressed Key's unicode value.

Note: In some cases one Key has more than one unicode value. In that case you will have to change the if statement in which you will check if codes array contains the primaryCode.

Upvotes: 2

Related Questions