【问题标题】:How to use custom Android ViewGroup in XML?如何在 XML 中使用自定义 Android ViewGroup?
【发布时间】:2011-05-04 13:43:42
【问题描述】:

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

当我从 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>

【问题讨论】:

  • 如果您包含完整的堆栈跟踪,您可能会获得更好的帮助。

标签: android user-interface


【解决方案1】:

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

如果没有这个,我所能做的就是将您指向 this sample project,它将 LinearLayout 扩展为自定义小部件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多