我应该叫超()或拨打本()为Android自定义视图的构造函数?自定义、视图、函数、Android

由网友(黑白棋局)分享简介:在创建自定义视图,我注意到很多人似乎不喜欢这样:When creating a custom view, I have noticed that many people seem to do it like this:public MyView(Context context) {super(context);//...

在创建自定义视图,我注意到很多人似乎不喜欢这样:

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?

有another部分对这个问题

推荐答案

这是确定。

当我们看的 TextView.java

When we look at the source of TextView.java.

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

They have used the same hierarchy.

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

So you are Okay with this approach.

阅读全文

相关推荐

最新文章