View的构造函数
一般来说,需要写前三个构造函数。那么问题来了,init的内容写在哪里呢?
通常情况下,应该这么写
第一个构造函数,在java代码中new这个view的时候会被调用
第二个构造函数,在xml中引用这个view的时候会被调用(就是刚刚发生的情况了)。AttributeSet对应的就是设置的属性值集合
第三个构造函数,在xml的theme、style中调用。它的作用是当没有为自定义的属性赋值的时候,就可以使用defStyleAttr里面定义的默认属性值。
通过这种写法,可以做到无论系统调用哪个构造函数,最后都会到第三个构造函数里面去,所以我们只要在第三个构造函数里写初始化语句就可以了
//java代码中new的时候调用
public TitleView(Context context) {
this(context, null);
}
// xml中引用时调用
public TitleView(Context context, AttributeSet attrs) {
this(context, attrs,0);(http://www.my516.com)
}
//theme、style时调用
public TitleView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
LayoutInflater.from(context).inflate(R.layout.view_title, this);
mBtnBack = findViewById(R.id.btn_back);
mTvTitle = findViewById(R.id.tv_title);
mIvHome = findViewById(R.id.iv_home);
mBtnBack.setOnClickListener(this);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
成啦!
自绘View
实现这样一个控件,每点击一次显示的数字加1;控件大小适应数字大小,周围可以设置padding。