Pascal Heude
Pascal Heude

Reputation: 5

Error while casting between Button and my custom class MyButton which extends Button

I'm developing an android application using Android Studio. I have written a custom class named 'MyButton' which extends Button. I also have a resource file with several buttons. At the execution, I get an exception saying that I cannot cast Button to MyButton. The line is :

myButton = (MyButton) view.findViewById(R.id.button1);

button1 is the id of a Button declared in the resource file. myButton is a data of type MyButton class.

Upvotes: 0

Views: 204

Answers (5)

Akef
Akef

Reputation: 369

Instead of doing this cast you can do the following:

First, Your MyButton class must use this constructor:

MyButton(Context context, AttributeSet attrs)

Then in your layout use your custom button:

<com.mypackagename.MyButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

Finally, you can refer to your custom button

MyButton button = findViewById(R.id.button);

Upvotes: 1

Masum
Masum

Reputation: 4959

You can not do this.

Because you created MyButton using Button. Button is independent but MyButton depends on Button. When you declare

MyButton button = (Button) findByElementById()

It causes Compiler error. Because Compiler knows MyButton is a Button Only Button is not MyButton.

But You can do like this

Button button = new MyButton()

Because MyButton() is a Button()

or

Button button = (Button) new MyButton() 

But Here You don't need cast MyButton() to Button() because Compiler already knows MyButton() is a Button()

In java you can only Upcasting and Downcasting. Have a look on Java Downcasting and Upcasting rules that will make you more clear

Upvotes: 1

sourav.bh
sourav.bh

Reputation: 467

As you didn't attach the layout source (XML), I am not sure if you used your custom MyButton class for creating a button like R.id.button1. You should do something like in your layout XML:

<your-package-name.MyButton
    android:id="@+id/button1"
    android:text="Coureur 1"
    android:clickable="true"
    android:text="Your button title"/>

Upvotes: 0

karan
karan

Reputation: 8853

Starting with API 26, findViewById() uses inference for its return type, so you don't need to cast. You can use below code for creating your object

MyButton myButton = (MyButton) view.findViewById(R.id.buttonCoureur1);

Upvotes: 0

Nanda Z
Nanda Z

Reputation: 1876

You can casting like this:

public class MyButton extends android.support.v7.widget.AppCompatButton {

    public MyButton(Context context) {
        super(context);
    }
}

MyButton myButton = findViewById(R.id.my_button);

API level 26 above does not require casting type declarations. As long as the child class still maintains the constructor must belong to the parent, there will be no errors

Upvotes: 0

Related Questions