How to change color of keys in KeyboardView Class

2019-02-14 07:25发布

问题:

This question already has an answer here:

  • How to change background color of key for android soft keyboard? 2 answers
  • How to change background color or theme of keys dynamically in Custom Keyboard Android 2 answers

I am working on a Custom Keyboard App. I need to set different themes for keys or background color in KeyboardView class and get key color at onCreateInputView() in SoftKeyboard extends InputMethodService Class.

However I am not getting how to get particular key according to keycode so I can change color or background of particular key.

回答1:

On any diffrent input layout use android:keyBackground=".."

example:

input.xml:

<com.example.KeyboardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/keyboard"
        android:layout_alignParentBottom="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:keyBackground="@drawable/blue_key"
        />

input1.xml:

<com.example.KeyboardView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/keyboard"
            android:layout_alignParentBottom="true"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:keyBackground="@drawable/red_key"
            />

then on OnCreateInputView method:

@Override public View onCreateInputView() {
    if(theme == 1)
        mInputView = (KeyboardView) getLayoutInflater().inflate(R.xml.input , null);
    else
        mInputView = (KeyboardView) getLayoutInflater().inflate(R.xml.input1 , null);
    mInputView.setOnKeyboardActionListener( this);
    mInputView.setKeyboard(mQwertyKeyboard);
    mComposing.setLength(0);
    return mInputView;
}

and on the end of the method onStartInput add this:

setInputView(onCreateInputView());

If you've already done it and what you need is to set a different background to special keys. Maybe the solution to my problem that I wrote will help you: https://stackoverflow.com/a/18354298/2683898

Good Luck! :)