2011-10-19 12 views
5

我試圖使用findViewById()獲取自定義視圖時遇到了問題。自定義視圖以其他方式顯示並正確運行。不幸的是,我需要能夠隨意更改它顯示的一些數據,因此必須完成。檢索自定義視圖時出現Android ClassCastException

我的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,而不是他們的它的子類的組件「查看」。

裏面我活動的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沒有麻煩給我一觀。但它不想給我一個圖表。

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

我可能只是在做一些愚蠢的事情。你們有什麼想法嗎?謝謝你的幫助!

+0

Chart是否有構造函數? – Phil

+0

是的。 Chart有全部3個構造函數。我編輯了我的帖子以顯示他們。 – Schmidget

回答

3

出於好奇,xml是否在<include>標記的另一個佈局中使用?

我有一個問題就這樣我們被包括在viewflipper另一個XML佈局

<include layout="@layout/some_layout.xml">和居然也得到了錯誤的部件。我不得不將整個外部佈局包裝在<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有關合並是如何工作的

+0

這個修好了!謝謝! – Schmidget

+0

非常感謝! – ArtemStorozhuk

-1

findViewById將始終返回View對象。您將只能訪問視圖類中指定的方法,而Chart類的方法都不會被訪問。

如果您需要訪問任何圖表特定方法或數據,您需要將視圖對象轉換爲圖表。

+0

就是這樣。將該View對象轉換爲Chart是什麼給了我ClassCastException。 – Schmidget

+0

Chart chart =(Chart)findViewById(R.id.chart);這會導致異常?嗯我很困惑,因爲它不應該導致這個錯誤。有時當這樣的錯誤發生時,我確定它不應該是錯誤的,我重新打開eclipse並清理項目。 – blessenm

+0

這就是我的想法。我認爲生成的代碼搞砸了,這似乎最近發生了很多。每隔一段時間,完美工作的代碼就會決定停止工作,因爲它不能再找到按鈕或其他東西。 我確實已經清理了該項目,但似乎沒有幫助。 – Schmidget

2

這是最有可能的錯誤。

解決方法:在Layout XML和findViewById()中爲CustomView使用一些新的'id'值。

+0

你是對的,爲我工作......謝謝 –