Java 检索自定义视图时出现Android ClassCastException

Java 检索自定义视图时出现Android ClassCastException,java,android,view,classcastexception,Java,Android,View,Classcastexception,在尝试使用findViewById()获取自定义视图时,我遇到了一个问题。否则,自定义视图将正确显示和操作。不幸的是,我需要能够随意更改它显示的一些数据,所以必须这样做 我的XML如下所示: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical

在尝试使用findViewById()获取自定义视图时,我遇到了一个问题。否则,自定义视图将正确显示和操作。不幸的是,我需要能够随意更改它显示的一些数据,所以必须这样做

我的XML如下所示:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <com.TheProject.TheApp.Chart 
    android:id="@+id/chart"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />

</LinearLayout>
这引发了ClassCastException

我决定做一点实验,改为看我是否仍然收到ClassCastException:

View chart=(View)findViewById(R.id.chart);
这很好,这告诉我findviewbyd很容易给我一个视图。但它不想给我一张图表

就Chart类而言,它是视图的一个非常简单的子类,在其他方面似乎工作正常

public class Chart extends View{
    public Chart(Context context) {
    super(context);     
    init();
}

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

public Chart(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);        
    init();     
}
    /* More stuff below like onDraw, onMeasure, setData, etc. */
}

我可能只是在做些傻事。你们有什么想法吗?谢谢你的帮助

findViewById将始终返回视图对象。您将只能访问视图类中指定的方法,并且图表类的任何方法都不能访问


如果需要访问任何特定于图表的方法或数据,则需要将视图对象强制转换为图表

只是出于好奇,该xml是否正在另一个带有
标记的布局中使用

我遇到了这样一个问题,我们在一个带有

findviewbyid
获取了错误的小部件。我必须将整个外部布局包装在
标记中,以允许它正确地合并到基本布局中

尝试将布局更改为该布局(如果包含)

<?xml version="1.0" encoding="utf-8"?>
<merge>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <com.TheProject.TheApp.Chart 
    android:id="@+id/chart"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />

</LinearLayout>
</merge>


编辑:查看合并的工作原理

这很可能是一个bug


解决方法:在布局XML和findViewById()中为CustomView使用一些新的“id”值。

图表是否有构造函数?是。图表包含所有3个构造函数。我编辑了我的帖子来展示给他们看,就是这样。将视图对象强制转换为一个图表是我得到ClassCastException的原因;这会导致异常吗?嗯,我很困惑,因为它不应该导致那个错误。有时,当我确信这样的错误不应该是错误时,我会重新打开eclipse并清理项目。这就是我所想的。我认为生成的代码出错了,这似乎是最近发生了很多。每隔一段时间,完美工作的代码就会决定停止工作,因为它再也找不到按钮或其他东西了。我已经清理了这个项目,但似乎没有任何帮助。我们试着从eclipse中删除这个项目。然后从现有资源创建一个新的android项目。或者您可能需要修改代码,比如更改文件名。或者尝试使用自定义视图创建一个小测试项目,看看是否仍然发生异常。
<?xml version="1.0" encoding="utf-8"?>
<merge>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

  <com.TheProject.TheApp.Chart 
    android:id="@+id/chart"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  />

</LinearLayout>
</merge>