java - Android.widget.RelativeLayout 无法转换为 android.widget.ImageView

标签 java android android-layout runtime-error classcastexception

我正在尝试获取在 XML 布局文件中定义的 ImageView 实例:

<RelativeLayout
    android:id="@+id/visual_compass_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/output_container" >

    <ImageView
        android:id="@+id/visual_compass"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:contentDescription="Compass"
        android:scaleType="fitStart"
        android:src="@drawable/compass_rose" />

</RelativeLayout>

但我总是遇到运行时错误:

... java.lang.ClassCastException: android.widget.RelativeLayout cannot be
cast to android.widget.ImageView ... at net.example.MainActivity.onCreate
(MainActivity.java:57)

“57”行就是那个:

compassView = (ImageView) findViewById(R.id.visual_compass);

我不明白为什么会抛出这个错误;我没有看到那段代码的问题。还有人知道吗?

谢谢你,Felix D。

最佳答案

确保在您的代码中 compassView 只是 ImageView 变量并尝试访问它作为

  ImageView compassView = (ImageView) findViewById(R.id.visual_compass); 

如果一切正常,则尝试从菜单 Project-> clean.Proejct-> Build 中再次清理并构建您的项目。

关于java - Android.widget.RelativeLayout 无法转换为 android.widget.ImageView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17688505/

相关文章:

java - 在java中实例化接口(interface)

java - 应该如何从 Spring Data Neo4j 6 中删除的 @Depth 注释迁移?

java - 如何在 Linux 终端中为 Java 使用 apache commons io?

android - dropbox-android-sync-sdk-1.0 中的问题

java - 无法导入 com.google.android.maps.MapView (Eclipse)

android - 无法在 intellij idea 的设计选项卡中看到 View

java - 线程和事务 : nested transactions not supported

java - 使用 Intent 打开 Assets 文件夹中的文件

java - 安卓/java : stop a method from returning value until a part of the method is executed

android - 每个选项卡上的复选框列表