簡體   English   中英

為什么我無法將View類型的對象投射到KeyboardView

[英]Why can't I cast an object of type View to KeyboardView

我已經定義了一個自定義的KeyboardView,如下所示:

    public class MyKeyboardView extends KeyboardView
    {
        public MyKeyboardView(Context context, AttributeSet attrs)
        {
            super(context, attrs);
            ...

在我的代碼中,我有:

    MyKeyboardView myKbView = (MyKeyboardView) myViewGroup.findViewWithTag("MyKeyboardView");

myViewGroup來自膨脹以下xml文件的位置:

    <?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>

這就是Logcat所說的:

    03-09 22:52:29.274: E/deliKey(21719): java.lang.ClassCastException:
    android.inputmethodservice.KeyboardView cannot be cast to
    com.parasum.delikey.MyKeyboardView

為什么?

在XML中將視圖聲明為android.inputmethodservice.KeyboardView ,您無法使用這種方式進行轉換。

您需要更改XML並將其聲明為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"/>

當前,您將可視元素聲明為KeyboardView類。 然后,您嘗試將其MyKeyboardViewMyKeyboardView類。 這不能工作,因為不能將一個類強制轉換為從其繼承的類(一個類不能強制轉換為其子類)。 這就是它在Java中的工作方式。

看來您不是在創建com.parasum.delikey.MyKeyboardView而是android.inputmethodservice.KeyboardView

嘗試替換布局xml中的行:

<android.inputmethodservice.KeyboardView

<com.parasum.delikey.MyKeyboardView

android.inputmethodservice.KeyboardView和com.parasum.delikey.MyKeyboardView確實都是View的后代,但兩者都不是View的后代。 它類似於視圖和字符串。 它們都是Object的后代,但是您不能在它們之間進行轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM