开发者

How to use custom Android ViewGroup in XML?

I have a class that extends FrameLayout called NoteView. It is a top level public class.

It works just fine when I'm creating the UI from java code, but I can't figure out how to use it in XML. I tried inserting the fully qualified class name just like I would for a custom view, but I get and exception ClassCastException: android.view.View cannot be cast to android.view.ViewGroup when activity tries to inflate the XML.

I have only been able to find tutorials on Custom Views, not custom viewgroups. What do I need to do to use a NoteView just like I would a FrameLayout in an XML Layout?

For example: This works

<?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>

But this throws the above exception:

<?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:开发者_StackOverflowlayout_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>


In the future, when complaining about exceptions, please consider including the full stack trace, particularly when people ask for the full stack trace, as the full stack trace may contain information that is relevant to giving you an answer. You can get the full stack trace via adb logcat, DDMS, or the DDMS perspective in Eclipse.

Lacking that, all I can do is point you to this sample project that extends a LinearLayout into a custom widget.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜