java.lang.ClassCastException: android.inputmethods

2019-09-15 07:43发布

问题:

I am getting this error while trying to use other layouts inside keyboard view as in my xml file. I don't want my keyboard layout to have rows and keys as in normal keyboard instead i want it to have two buttons on either side at the top inside any parent layout. Also I need a layout inside keyboard view to contain my drawing canvas.

I have also tried to put in a layout like this:

<?xml version="1.0" encoding="utf-8"?>
<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:keyBackground="@drawable/square_rounded"
    android:background="#ffffff">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:id="@+id/mainLinearLayout">

    <RelativeLayout
        android:id="@+id/keyboardLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <Button
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:text="Cancel"
            android:layout_alignParentLeft="true">
        </Button>

        <Button
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:text="Done"
            android:layout_alignParentRight="true">
        </Button>

        <LinearLayout
            android:layout_alignParentTop="true"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </LinearLayout>
    </RelativeLayout>
</LinearLayout>
</android.inputmethodservice.KeyboardView>

and then tried loading it like:

       kv = (KeyboardView)getLayoutInflater()
        .inflate(R.layout.draw_signature, null);
        kv.setOnKeyboardActionListener(this);
        kv.setPreviewEnabled(false);
        return kv;

Any help or a tutorial link would be appreciated.

回答1:

You get the error because KeyboardView extends View , which cannot contain children like ViewGroup.

In order to make it work you need to create a separate layout file with your keyboard layout and then add it to the KeyboardView like this:

<android.inputmethodservice.KeyboardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/keyboard"
    ...
    android:keyPreviewLayout ="@layout/your_keyboard_layout">

For full tutorial how to customize keyboard : https://code.tutsplus.com/tutorials/create-a-custom-keyboard-on-android--cms-22615