gpt4 book ai didi

java - 如何使用我的自定义 TextView 转换 TextView?

转载 作者:太空宇宙 更新时间:2023-11-03 12:39:48 27 4
gpt4 key购买 nike

我从这里获取 TextView 实例:

    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;

我得到了这个异常(exception):

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

最佳答案

您的 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"
...
/>

class-path 的正确性非常重要!

关于java - 如何使用我的自定义 TextView 转换 TextView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10681235/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com