0

I have a simple app which will have a bunch of EditTexts taking numeric values, and various calculations between them. Like a unit conversion tool.

So I've defined CalcField as a subclass of EditText to serve as a field that contains only float values, with some extra methods, for example:

package com.example.ex1;
import android.content.Context;
import android.widget.*;
public class CalcField extends EditText {

// no idea why this is needed.  without it i'm told an explicit constructor needed.
public CalcField(Context c) {
    super(c);
}

public void setValue(float d) {
    setText(String.valueOf(d));
}
public float getValue() {
    return Float.valueOf(getText().toString());
}
}

==

In my layout I have a field X defined like this:

        <EditText
            android:id="@+id/X"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ems="10"
            android:inputType="numberDecimal" />

And in my main activity I try to grab this field from my layout, like this:

    CalcField fieldX = (CalcField) findViewById(R.id.X);

Which gives a class cast exception that I don't understand:

07-16 21:23:49.049: E/AndroidRuntime(1429): FATAL EXCEPTION: main
07-16 21:23:49.049: E/AndroidRuntime(1429): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ex1/com.example.ex1.MainActivity}: java.lang.ClassCastException: android.widget.EditText cannot be cast to com.example.ex1.CalcField
07-16 21:23:49.049: E/AndroidRuntime(1429):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)

Can anyone tell me why I can't do this simple typecast?

Thanks in advance

1 Answer 1

4

Change this

       <EditText
        android:id="@+id/X"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal" />

to

        <com.example.ex1.CalcField
        android:id="@+id/X"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal" />
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, add add the constructor (Context, AttributeSet) I think.
Thanks a lot, I'll try that. Any suggestion for the best place/way to learn about this stuff?

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.