首页 > 代码库 > 回顾自定义view三个构造函数
回顾自定义view三个构造函数
public class MyCustomView extends View { //第一个构造函数 public MyCustomView(Context context) { this(context, null); } //第二个构造函数 public MyCustomView(Context context, AttributeSet attrs) { this(context, attrs, 0); } //第三个构造函数 public MyCustomView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO:获取自定义属性 } .... }
关于三个构造函数使用时机的说法
- 在代码中直接new一个Custom View实例的时候,会调用第一个构造函数.这个没有任何争议.
- 在xml布局文件中调用Custom View的时候,会调用第二个构造函数.这个也没有争议.
- 在xml布局文件中调用Custom View,并且Custom View标签中还有自定义属性时,这里调用的还是第二个构造函数.
也就是说,系统默认只会调用Custom View的前两个构造函数,至于第三个构造函数的调用,通常是我们自己在构造函数中主动调用的(例如,在第二个构造函数中调用第三个构造函数).
回顾自定义view三个构造函数
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。