在XML布局自定义视图 [英] Custom view in xml layout

查看:187
本文介绍了在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>

什么我错过了?

What have I missed?

修改

更多信息

我的看法是这样的

package com.chainparticles;
public class ChainView extends SurfaceView implements SurfaceHolder.Callback {
    public ChainView(Context context) {
        super(context);
        getHolder().addCallback(this);
    }
// Other stuff
}

和它工作正常是这样的:

And it works fine like this:

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>

编辑:

看到你的$ C $的其余部分C中,它可能是扔,因为你不能叫 getHolder 在构造函数中,同时被充气后。此举为查看#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);
}

如果不工作,尝试将在您在活动调用init函数取值的onCreate后的setContentView

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

这可能是工作,因为从XML构造函数时,充气前: 视图(上下文,AttributeSet中)被调用,而不是视图(上下文)

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天全站免登陆