2010-07-10 70 views
3

我有一個擴展名爲NoteView的FrameLayout的類。 這是一個頂級的公共課。如何在XML中使用自定義的Android ViewGroup?

它工作得很好,當我從Java代碼創建UI時,但我無法弄清楚如何在XML中使用它。我嘗試插入完全限定的類名稱,就像我爲自定義視圖一樣,但當活動試圖膨脹XML時,我得到並例外ClassCastException: android.view.View cannot be cast to android.view.ViewGroup

我只能在自定義視圖上找到教程,而不是自定義視圖組。我需要做什麼才能像使用XML佈局中的FrameLayout一樣使用NoteView?

例如:該作品

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
<test.cjb.sandbox.NoteView 
android:id="@+id/noteview" 
android:layout_width="fill_parent" 
android:layout_height="100dp" 
android:background="#FF0000" 
android:layout_gravity="right"> 
</test.cjb.sandbox.NoteView> 
    <Button 
    android:id="@+id/button" 
    android:layout_width="100dp" 
    android:layout_height="fill_parent" 
    android:text="Sibling Button"/> 
</LinearLayout> 

但是,這將引發上述異常:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 
<test.cjb.sandbox.NoteView 
android:id="@+id/noteview" 
android:layout_width="fill_parent" 
android:layout_height="100dp" 
android:background="#FF0000" 
android:layout_gravity="right"> 
    <Button 
    android:id="@+id/button" 
    android:layout_width="100dp" 
    android:layout_height="fill_parent" 
    android:text="Child Button"/> 
</test.cjb.sandbox.NoteView> 

</LinearLayout> 
+0

如果包含完整的堆棧跟蹤,您可能會有更好的運氣獲得幫助。 – CommonsWare 2010-07-10 20:57:00

回答

2

在未來,抱怨異常時,請考慮包括完整的堆棧跟蹤,尤其是人的時候請求完整的堆棧跟蹤,因爲完整的堆棧跟蹤可能包含與給出答案有關的信息。您可以通過adb logcat,DDMS或Eclipse中的DDMS透視圖獲得完整的堆棧跟蹤。

由於缺乏這一點,我所能做的就是將您指向this sample project,將LinearLayout擴展爲自定義小部件。

相關問題