我通过创建 SurfaceView 类的子类创建了自己的 View 。
但是我不知道如何从 xml 布局文件中添加它。我当前的 main.xml 如下所示:
<?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>
我错过了什么?
编辑
更多信息
我的观点是这样的
package com.chainparticles;
public class ChainView extends SurfaceView implements SurfaceHolder.Callback {
public ChainView(Context context) {
super(context);
getHolder().addCallback(this);
}
// Other stuff
}
它像这样工作得很好:
ChainView cview = new ChainView(this);
setContentView(cview);
但是当尝试从 xml 中使用它时没有任何反应。
最佳答案
你想要:
<?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>
编辑:
在看到您的其余代码后,它可能会抛出错误,因为您无法在膨胀时在构造函数中调用 getHolder
。将其移动到 View#onFinishInflate
所以:
@Override
protected void onFinishInflate() {
getHolder().addCallback(this);
}
如果这不起作用,请尝试将其放入您在 setContentView
之后在 Activity
的 onCreate 中调用的初始化函数中。
它之前可能是有效的,因为当从 xml 构造函数膨胀时:
View(Context, AttributeSet)
被调用而不是 View(Context)
。
关于android - xml 布局中的自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3260876/