Android.widget.RelativeLayout无法强制转换为android.widget.ImageView

时间:2013-07-16 23:12:55

标签: 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。

1 个答案:

答案 0 :(得分:5)

请确保代码中的compassView仅为ImageView变量,并尝试将其作为

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

如果一切正确,请尝试从菜单Project-> clean.Proejct-> Build再次清理和构建项目。

相关问题