1

I have a project where I am trying to make a subclass to ImageView, to add some methods I want to use. I'm only a couple of weeks into Android coding so I'm not very experienced, and fairly new to OOP. As I couldn't get it to work in my main project I made a small test project, alas, I get the same error.

First I created a new class ImageViewCustom.java that extends ImageView

public class ImageViewCustom extends ImageView {}

(I have added the constructors from the super class)

In the XML I did like so after reading here

<ImageView class="com.example.testcustomclass.ImageViewCustom" 
    android:id="@+id/imageViewCustom" ... />

This works to build and run, but then when I try to reference it in MainActivity like so

ImageViewCustom imageViewTest = (ImageViewCustom)
    findViewById(R.id.imageViewCustom);

I get...

FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example.testcustomclass.MainActivity}:
    java.lang.ClassCastException: android.widget.ImageView 
    cannot be cast to com.example.testcustomclass.ImageViewCustom

What am I doing wrong? D: I assume I am missing something very basic as this is an almost empty project. FYI I'm trying to get an assignment done by tonight (eh!) and got so much duplicate code I wanted to do a subclass, but I am stumped and stressed out >_< lack of sleep etc.

(edit, fixing code formatting...)

2 Answers 2

3

Well your XML is off... I always use

<com.my.project.MyView
     android:id="..."
/>

which I believe is the proper way to do so.

Sign up to request clarification or add additional context in comments.

1 Comment

That works, apparently I did the problem solving the wrong way in that link I provided, haha. Talk about confusion, thanks! xD
0

If your referencing your view in a xml layout you don't need to use class

replace

<ImageView class="com.example.testcustomclass.ImageViewCustom" 
    android:id="@+id/imageViewCustom" ... />

with

<com.example.testcustomclass.ImageViewCustom
    android:id="@+id/imageViewCustom" ... />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.