简体   繁体   中英

Android.widget.RelativeLayout cannot be cast to android.widget.ImageView

I'm trying to get the instance of a ImageView defined in an XML layout file:

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

But I always get that runtime error:

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

Line "57" is that one:

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

I can't figure out why that error ist thrown; I don't see the problem with that piece of code. Does anybody elso know?

Thank you, Felix D.

Make sure in your code the compassView is ImageView variable only and try to access it as

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

And if everything is correct then try to clean and Build your project again from the menu Project-> clean. and Proejct-> Build .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM