Android 自定义视图是否需要所有三个构造函数? [英] Do I need all three constructors for an Android custom view?

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

问题描述

在创建自定义视图时,我注意到很多人似乎是这样做的:

When creating a custom view, I have noticed that many people seem to do it like this:

public MyView(Context context) {
  super(context);
  // this constructor used when programmatically creating view
  doAdditionalConstructorWork();
}

public MyView(Context context, AttributeSet attrs) {
  super(context, attrs);
  // this constructor used when creating view through XML
  doAdditionalConstructorWork();
}

private void doAdditionalConstructorWork() {

  // init variables etc.
}

我的第一个问题是,构造函数 MyView(Context context, AttributeSet attrs, int defStyle) 怎么样?我不确定它在哪里使用,但我在超类中看到它.我需要它吗?用在什么地方?

My first question is, what about the constructor MyView(Context context, AttributeSet attrs, int defStyle)? I'm not sure where it is used, but I see it in the super class. Do I need it, and where is it used?

还有 另一部分问题.

推荐答案

如果您将从 xml 添加自定义 View 也喜欢:

If you will add your custom View from xml also like :

 <com.mypack.MyView
      ...
      />

您将需要构造函数 public MyView(Context context, AttributeSet attrs),否则当 Android 尝试扩充您的 View 时,您将收到 Exception代码>.

you will need the constructor public MyView(Context context, AttributeSet attrs), otherwise you will get an Exception when Android tries to inflate your View.

如果您从 xml 添加您的 View 并指定 android:style 属性,如:

If you add your View from xml and also specify the android:style attribute like :

 <com.mypack.MyView
      style="@styles/MyCustomStyle"
      ...
      />

在应用显式 XML 属性之前,还将调用第二个构造函数并将样式默认为 MyCustomStyle.

the 2nd constructor will also be called and default the style to MyCustomStyle before applying explicit XML attributes.

当您希望应用程序中的所有视图具有相同的样式时,通常会使用第三个构造函数.

The third constructor is usually used when you want all of the Views in your application to have the same style.

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

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