Java 如何使用自定义文本视图强制转换文本视图?
我从这里获取文本视图实例:Java 如何使用自定义文本视图强制转换文本视图?,java,android,Java,Android,我从这里获取文本视图实例: TextView date = null; try { date = (TextView) getLayoutInflater().inflate( R.layout.some_textview, null); } catch (Exception e) { // TODO: handle exception e.p
TextView date = null;
try {
date = (TextView) getLayoutInflater().inflate(
R.layout.some_textview, null);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
我创建了我的自定义文本视图:
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
,仍然会得到相同的异常,这是我的一些\u textview的xml:
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);
}
}
<?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
。您试图将TextView对象强制转换为TextView的子类,但该对象不是子类类型()的实例。请尝试使用如下方法:
MyTextView date = null;
try {
date = (MyTextView) getLayoutInflater().inflate(
R.layout.some_textview, null);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
您可以直接在XML中使用MyTextView,而不是
使用
然后在您的代码中使用com.myapp.name.MyTextView而不是TextView。您的XML布局是否正确 不要使用
<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"
...
/>
这是非常重要的类路径是正确的 执行此操作
MyTextView日期=(MyTextView)GetLayoutFlater()代码>