android - xml 布局中的自定义 View

标签 android xml layout

我通过创建 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/

相关文章:

android - 构建成功,但无法使用 "adb reverse"spawnSync adb ENOENT 连接到开发服务器

android - 使用 JTwitter 转发和回复

java - 必须在项目中设置 build.dir 错误

java - mvn包不包含xml

iphone - 缩放文本以适合 iPhone

android - JQueryMobile - 样式未应用于 Webview (Android)

android xml选择器不起作用

android - XML 中查看动画的引用自定义插值器

silverlight - 如何在 WP7 上实现相机应用风格的照片条?

wpf - 居中 WPF 控件