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

时间:2011-10-19 03:17:39

标签: java android view classcastexception

尝试使用findViewById()抓取自定义View时,我遇到了一个问题。否则,自定义视图将正确显示和运行。不幸的是,我需要能够随意更改它显示的一些数据,因此必须完成它。

我的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>

我知道有时问题是人们不小心将XML中的组件命名为“View”而不是它们的子类。

在我的Activity的onCreate()方法中,我有这个:

myChart=(Chart)findViewById(R.id.chart); //where myChart is an object of type Chart

抛出ClassCastException。

我决定尝试一下,然后将行更改为此,以查看我是否仍然收到了ClassCastException:

View chart=(View)findViewById(R.id.chart);

这很好用,告诉我findViewById给我一个View没有问题。但它不想给我一张图表。

就Chart类而言,它是View的一个非常简单的子类,看起来可以正常工作。

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. */
}

我可能只是在做一些愚蠢的事情。你们有什么想法吗?谢谢你的帮助!

3 个答案:

答案 0 :(得分:3)

出于好奇,xml是否在另一个带有<include>标签的布局中使用?

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

的viewflipper中包含了另一个xml布局

<include layout="@layout/some_layout.xml">findviewbyid获取了错误的小部件。我必须将整个外部布局包装在<merge></merge>标签中,以允许它正确地合并到基本布局中。

尝试将布局更改为此布局(如果已包含在内)。

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

修改:查看this link有关合并的工作原理

答案 1 :(得分:2)

这很可能是一个错误。

要解决的解决方法:使用一些新的&#39; id&#39;布局XML中的CustomView的值和findViewById()。

答案 2 :(得分:-1)

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

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