我試圖使用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. */
}
我可能只是在做一些愚蠢的事情。你們有什麼想法嗎?謝謝你的幫助!
Chart是否有構造函數? – Phil
是的。 Chart有全部3個構造函數。我編輯了我的帖子以顯示他們。 – Schmidget