xml 布局中的自定义视图 [英] Custom view in xml layout

查看:23
本文介绍了xml 布局中的自定义视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过创建 SurfaceView 类的子类创建了自己的视图.

I've created my own view by creating a subclass of the SurfaceView class.

但是我不知道如何从 xml 布局文件中添加它.我当前的 main.xml 看起来像这样:

However I can't figure out how to add it from the xml layout file. My current main.xml looks like this:

<?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 中使用它时没有任何反应.

But nothing happens when trying to use it from the 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

After seeing the rest of your code it's probably throwing because you can't call getHolder in the constructor while being inflated. Move that to View#onFinishInflate

所以:

@Override
protected void onFinishInflate() {
    getHolder().addCallback(this);
}

如果这不起作用,请尝试将其放入在 setContentView 之后在 Activity 的 onCreate 中调用的 init 函数中.

If that doesn't work try putting that in an init function that you call in your Activitys onCreate after setContentView.

它之前可能有效,因为当从 xml 膨胀构造函数时:View(Context, AttributeSet) 代替 View(Context) 被调用.

It was probably working before because when inflating from xml the constructor: View(Context, AttributeSet) is called instead of View(Context).

这篇关于xml 布局中的自定义视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆