Both android.inputmethodservice.KeyboardView and com.parasum.delikey.MyKeyboardView are indeed descendants of View, but neither is a descendant of the other. It's analogous to Views and Strings. They're both descendants of Object, but you can't cast between them.
Why can't I cast an object of type View to KeyboardView
-
11-06-2023 - |
문제
I have defined a custom KeyboardView like this:
public class MyKeyboardView extends KeyboardView
{
public MyKeyboardView(Context context, AttributeSet attrs)
{
super(context, attrs);
...
and somewhere in my code I have:
MyKeyboardView myKbView = (MyKeyboardView) myViewGroup.findViewWithTag("MyKeyboardView");
where myViewGroup comes from inflating the following xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<android.gesture.GestureOverlayView
android:id="@+id/gestureOverlayView"
android:gestureColor="#00000000"
android:layout_width="match_parent"
android:tag="MyGestureOverlayView"
android:layout_height="wrap_content">
<android.inputmethodservice.KeyboardView
android:id="@+id/keyboard"
android:keyBackground="@drawable/orange_keyboard_keys_background"
android:keyTextColor="#ff8710"
android:background="#4c4c4c"
android:tag="MyKeyboardView"
android:keyTextSize="21sp"
android:keyPreviewLayout="@layout/key_preview_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.gesture.GestureOverlayView>
</LinearLayout>
and this is what Logcat says:
03-09 22:52:29.274: E/deliKey(21719): java.lang.ClassCastException:
android.inputmethodservice.KeyboardView cannot be cast to
com.parasum.delikey.MyKeyboardView
WHY?
해결책
다른 팁
It looks like you are not creating a com.parasum.delikey.MyKeyboardView
but rather a android.inputmethodservice.KeyboardView
.
Try replacing the line in your layout xml:
<android.inputmethodservice.KeyboardView
with
<com.parasum.delikey.MyKeyboardView
You cannot cast this way as you declared the view in XML as android.inputmethodservice.KeyboardView
.
You need to change your XML and declare it as MyKeyboardView
:
<com.parasum.delikey.MyKeyboardView
android:id="@+id/keyboard"
android:keyBackground="@drawable/orange_keyboard_keys_background"
android:keyTextColor="#ff8710"
android:background="#4c4c4c"
android:tag="MyKeyboardView"
android:keyTextSize="21sp"
android:keyPreviewLayout="@layout/key_preview_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
You currently declare your visual element as KeyboardView
class. Then you try to cast it to MyKeyboardView
class. This cannot work as a class cannot be cast to a class that inherits from it (a class cannot be cast to its child class). This is the way it works in Java.