如何使用我的自定义TextView来创建TextView?

3
我从这里获取文本视图实例:
```

我从这里获取文本视图实例:

```
    TextView date = null;

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

        } 

我创建了自定义TextView:

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);
    }


}

现在我想转换这些内容:
MyTextView my = (MyTextView)date;

我遇到了一个异常:

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

那么应该怎么做呢?

谢谢。

编辑:

如果我将date声明为MyTextView,仍然会出现相同的异常,这是some_textview的xml:

<?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"  
        />

MyTextView date = (MyTextView) getLayoutInflater().inflate(R.layout.some_textview, null); - Ron
4个回答

4
您的XML布局R.layout.some_textview资源是否正确?请勿使用

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

您需要在XML中使用自定义类:

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

非常重要的一点是要确保类路径正确!


2

您可以直接在XML中使用您的MyTextView,而不是使用<TextView />,请使用<com.myapp.name.MyTextView />

然后在您的代码中使用com.myapp.name.MyTextView代替TextView。


0

尝试在此处使用:

    MyTextView date = null;

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

    } 

0

你应该将date声明为MyTextView。你试图将TextView对象转换为TextView的子类,但该对象不是子类类型的实例(请参见示例)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接