java - 为什么我不能将 View 类型的对象转换为 KeyboardView

标签 java android android-layout android-view

我定义了一个像这样的自定义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

为什么?

最佳答案

android.inputmethodservice.KeyboardView 和 com.parasum.delikey.MyKeyboardView 确实都是 View 的后代,但都不是另一个的后代。它类似于 View 和字符串。它们都是 Object 的后代,但不能在它们之间进行转换。

关于java - 为什么我不能将 View 类型的对象转换为 KeyboardView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22287032/

相关文章:

java - 如何区分 ehcache 中的生存时间和空闲时间

java - SpringMVC错误 "EL1044E: Unexpectedly ran out of input"

android - 使用自定义选择器时删除默认单选按钮复选框

java - 当我运行应用程序时 android.support.v7.widget.CardView 不显示

android - 自定义 ViewGroup 中的 View 在大小更改后未呈现

java - Android - 以编程方式相对布局

java - 在数组中除最后一项之外的项之间插入分号

java - 使用 Webfilter 时 Keycloak 刷新过期 token

java - RxJava - 单机无法运行

android - 什么时候在 Android 中使用 HTML5?什么时候不用?