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

查看:163
本文介绍了我需要的所有三个构造一个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的(上下文的背景下,ATTRS的AttributeSet,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?

有<一href="http://stackoverflow.com/questions/9195785/should-i-call-super-or-call-this-for-android-custom-view-constructors">another部分对这个问题。

推荐答案

如果您可以添加自定义的查看 XML 还喜欢:

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

 <com.mypack.MyView
      ...
      />

您将需要构造公共MyView的(上下文的背景下,AttributeSet中的ATTRS),否则你将得到一个异常当机器人试图夸大你的查看

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 ,也spcify的安卓风格属性,如:

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

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

您还需要第三个构造公共MyView的(上下文的背景下,ATTRS的AttributeSet,INT defStyle)

第三个构造函数通常用于当你扩展风格键,自定义,然后你想设置的风格来给定查看在你的布局。

The third constructor is usually used when you extend a style and customize it, and then you would like to set that style to a given View in your layouts.

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

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