Android 自定义视图构造函数 [英] Android Custom View Constructor

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

问题描述

我正在从以下方面学习如何使用自定义视图:

I'm learning about using Custom Views from the following:

http://developer.android.com/guide/主题/ui/custom-components.html#modifying

描述说:

类初始化一如既往,super 首先被调用.此外,这不是默认构造函数,而是一个参数化的.编辑文本是使用这些参数创建时从 XML 布局文件膨胀,因此,我们的构造函数需要同时拿走它们并将它们传递给超类构造函数也是如此.

Class Initialization As always, the super is called first. Furthermore, this is not a default constructor, but a parameterized one. The EditText is created with these parameters when it is inflated from an XML layout file, thus, our constructor needs to both take them and pass them to the superclass constructor as well.

有更好的描述吗?我一直在试图弄清楚构造函数应该是什么样子,并且我提出了 4 种可能的选择(参见文章末尾的示例).我不确定这 4 个选择做什么(或不做什么),为什么我应该实现它们,或者参数的含义.有这些描述吗?

Is there a better description? I've been trying to figure out what the constructor(s) should look like and I've come up with 4 possible choices (see example at end of post). I'm not sure what these 4 choices do (or don't do), why I should implement them, or what the parameters mean. Is there a description of these?

public MyCustomView()
{
    super();
}

public MyCustomView(Context context)
{
    super(context);
}

public MyCustomView(Context context, AttributeSet attrs)
{
    super(context, attrs);
} 

public MyCustomView(Context context, AttributeSet attrs, Map params)
{
    super(context, attrs, params);
} 

推荐答案

你不需要第一个,因为那是行不通的.

You don't need the first one, as that just won't work.

第三个意味着您的自定义 View 可以从 XML 布局文件中使用.如果你不关心这个,你就不需要它.

The third one will mean your custom View will be usable from XML layout files. If you don't care about that, you don't need it.

第四个是错误的,AFAIK.没有将 Map 作为第三个参数的 View 构造函数.有一个将 int 作为第三个参数,用于覆盖小部件的默认样式.

The fourth one is just wrong, AFAIK. There is no View constructor that take a Map as the third parameter. There is one that takes an int as the third parameter, used to override the default style for the widget.

我倾向于使用 this() 语法来组合这些:

I tend to use the this() syntax to combine these:

public ColorMixer(Context context) {
    this(context, null);
}

public ColorMixer(Context context, AttributeSet attrs) {
    this(context, attrs, 0);
}

public ColorMixer(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    // real work here
}

您可以在本书示例中查看此代码的其余部分.

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

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