Custom view in xml layout
我通过创建SurfaceView类的子类来创建自己的视图。
但是我不知道如何从xml布局文件中添加它。我当前的main.xml看起来像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <?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" > <View class="com.chainparticles.ChainView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> |
我错过了什么?
编辑
更多信息
我的视图看起来像这样
1 2 3 4 5 6 7 8 | package com.chainparticles; public class ChainView extends SurfaceView implements SurfaceHolder.Callback { public ChainView(Context context) { super(context); getHolder().addCallback(this); } // Other stuff } |
它可以像这样正常工作:
1 2 | ChainView cview = new ChainView(this); setContentView(cview); |
但是尝试从xml使用它时什么也没有发生。
您要:
1 2 3 4 5 6 7 8 9 10 11 12 | <?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" > <com.chainparticles.ChainView android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> |
编辑:
看到其余的代码后,可能会抛出该错误,因为您在膨胀时无法在构造函数中调用
所以:
1 2 3 4 | @Override protected void onFinishInflate() { getHolder().addCallback(this); } |
如果这样不起作用,请尝试将其放在您在
它以前可能是起作用的,因为从xml构造函数膨胀时:
调用
在示例中您错过的是标记名称,它应该是"视图"(第一个非大写的)而不是"视图"。尽管您通常可以将类名用作标记名,但是如果您的类是内部类,则不可能这样做,因为XML标记中限制了Java中用于引用内部类的" $"符号。
因此,如果要在XML中使用内部类,则应这样编写:
1 2 3 4 5 6 7 8 9 10 11 12 13 | <?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" > <view class="com.chainparticles.Foo$InnerClassChainView" android:layout_width="fill_parent" android:layout_height="fill_parent" /> </LinearLayout> |
问题是架构中同时存在"视图"和"视图"标记。" View"标签(以大写字母开头)将生成一个View类,而" view"标签在解析后将检查类属性。