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

5
我有一个继承自FrameLayout的类,叫做NoteView。它是一个顶级公共类。
当我从Java代码创建UI时,它可以正常工作,但我不知道如何在XML中使用它。我尝试像自定义视图一样插入完全限定的类名,但当Activity尝试填充XML时,我会收到异常“ClassCastException:android.view.View无法转换为android.view.ViewGroup”。
我只能找到关于自定义视图的教程,没有关于自定义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>

1
如果你包含了完整的堆栈跟踪信息,那么你可能会更容易地得到帮助。 - CommonsWare
1个回答

4
在未来,如果您抱怨异常,请考虑包含完整的堆栈跟踪,特别是当人们要求完整的堆栈跟踪时,因为完整的堆栈跟踪可能包含与给您答案相关的信息。您可以通过adb logcat、DDMS或Eclipse中的DDMS透视图获取完整的堆栈跟踪。
如果没有这个,我只能指向这个示例项目,它将一个LinearLayout扩展为自定义小部件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接