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

14,069

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.

Share:
14,069
felixd
Author by

felixd

Updated on June 04, 2022

Comments

  • felixd
    felixd almost 2 years

    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.