How to distinguish TextView with my custom TextView?

I take the text from an example:

    TextView date = null;

        try {
            date = (TextView) getLayoutInflater().inflate(
                    R.layout.some_textview, null);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        } 

I created my own text view:

public class MyTextView extends TextView{

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public MyTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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


}

Now I want to use those:

MyTextView my = (MyTextView)date;

I get exeption for this:

 java.lang.ClassCastException: android.widget.TextView cannot be cast to com.myapp.name.MyTextView

So how should this be done?

Thank.

Edit:

If I declare datehow MyTextView, I still get the same exception, ther is my xml some_textview:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="This is a template for date text view"  
        />
+3
source share
4 answers

Is the resource of your XML layout correct R.layout.some_textview?

Do not use

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ...
    />

You should use your own class in your XML:

<com.your.package.MyTextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ...
    />

It is very important that the class path is correct!

+4
source

You can directly use MyTextView in XML, instead of <TextView />using<com.myapp.name.MyTextView />

Then in your code use com.myapp.name.MyTextView instead of TextView.

+2

You must declare datehow MyTextView. You tried to apply a TextView object to a subclass of TextView, but the object is not an instance of a subclass type ( see Example ).

0
source

Try using as here:

    MyTextView date = null;

    try {
        date = (MyTextView) getLayoutInflater().inflate(
                R.layout.some_textview, null);
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();

    } 
0
source

All Articles