注意引入命名空间
:
xmlns:app=“http://schemas.android.com/apk/res-auto”
2.添加构造方法
新建一个RandomTextView
类,继承View
,并添加3
个构造方法
class RandomTextView : View {
//文本
private var mRandomText: String
//文本颜色
private var mRandomTextColor: Int = 0
//文本字体大小
private var mRandomTextSize: Int = 0
private var paint = Paint()
private var bounds = Rect()
//调用两个参数的构造
constructor(context: Context) : this(context, null)
//xml默认调用两个参数的构造,再调用三个参数的构造,在三个参数构造里获取自定义属性
constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)
constructor(context: Context, attributeSet: Attr
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
浏览器打开:qq.cn.hn/FTe 免费领取
ibuteSet?, defStyle: Int) : super(context, attributeSet, defStyle) {
…
}
…
}
这里要注意的是,所有的构造方法,都指向的是第三个构造方法,前两个构造的继承是this
,而不是super
。
第一个构造比如我们可以是new创建的,第二个是xml中默认调用的,我们在第三个构造中去获取自定义属性。
3.在构造里获取自定义样式
constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(context, attributeSet, defStyle) {
//获取自定义属性
val typedArray