如何在 XML 中使用自定义 Android ViewGroup?

Cod*_*ile 5 user-interface android

我有一个扩展 FrameLayout 的类,称为 NoteView。这是一个顶级的公开课。

当我从 java 代码创建 UI 时它工作得很好,但我不知道如何在 XML 中使用它。我尝试插入完全限定的类名,就像插入自定义视图一样,但是ClassCastException: android.view.View cannot be cast to android.view.ViewGroup当活动尝试膨胀 XML 时,出现异常。

我只能找到有关自定义视图的教程,而不是自定义视图组。我需要做什么才能像在 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>
Run Code Online (Sandbox Code Playgroud)

但这会引发上述异常:

<?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>
Run Code Online (Sandbox Code Playgroud)

Com*_*are 4

将来,当抱怨异常时,请考虑包括完整的堆栈跟踪,特别是当人们要求完整的堆栈跟踪时,因为完整的堆栈跟踪可能包含与给您答案相关的信息。adb logcat您可以通过DDMS 或 Eclipse 中的 DDMS 透视图获取完整的堆栈跟踪。

如果缺少这一点,我所能做的就是向您指出这个将 a 扩展到自定义小部件的示例项目。LinearLayout