我应该叫超()或拨打本()为Android自定义视图的构造函数? [英] Should I call super() or call this() for android custom view constructors?

查看:135
本文介绍了我应该叫超()或拨打本()为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.
}

我这个问题是它阻止我从我的决策变量决赛。任何理由不做到以下几点?

My problem with this is that it stops me from making my variables final. Any reason not to do the following?

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

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

public MyView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  // this constructor used where?
  // init variables
}

我已经能够通过XML,并通过code创建视图就好了,但我不知道是否有任何缺点这种方法。将这项工作在所有情况下?

I've been able to create the view just fine through XML and through code, but I'm not sure if there are any drawbacks to this approach. Will this work in all cases?

有<一个href=\"http://stackoverflow.com/questions/9195713/do-i-need-all-three-constructors-for-an-android-custom-view\">another部分对这个问题

推荐答案

这是确定。

当我们看的<一个源href=\"http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android/4.0.3_r1/android/widget/TextView.java#TextView.%3Cinit%3E%28android.content.Context%29\"相对=nofollow> TextView.java

When we look at the source of TextView.java.

他们已使用了相同的分层结构。

They have used the same hierarchy.

那么,你是好了这种方法。

So you are Okay with this approach.

这篇关于我应该叫超()或拨打本()为Android自定义视图的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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