您的位置:首页 > 其它

回顾自定义view三个构造函数

2017-04-21 21:58 176 查看
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的前两个构造函数,至于第三个构造函数的调用,通常是我们自己在构造函数中主动调用的(例如,在第二个构造函数中调用第三个构造函数).

  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: