【问题标题】:How to Send Argument Through Super After Being Defined In Subclass?在子类中定义后如何通过super发送参数?
【发布时间】:2019-11-19 22:46:11
【问题描述】:
我想通过 super 将 attrs 发送到 View 中。 (如第一行所示)但是IDE不想带它;我的代码中遗漏了一些东西。
class BoxDrawingView(context: Context): View(context, attrs) {
var attrs: AttributeSet? = null
constructor(context: Context, attrs: AttributeSet): this(context) {
this.attrs = attrs
}
}
谁能帮我解决这个问题?谢谢!
【问题讨论】:
标签:
android
kotlin
android-view
android-custom-view
【解决方案1】:
试试这个:
class BoxDrawingView : View {
var attrs: AttributeSet? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
this.attrs = attrs
}
}
问题是您没有一个适用于所有情况的构造函数。发生这种情况时,您可以避免使用普通的构造函数简写(即在类声明中内联声明属性),创建多个构造函数,并让每个构造函数委托给不同的超类构造函数。
如果您希望将 attrs 声明为 val 而不是 var,您也可以稍微修改:
class BoxDrawingView : View {
val attrs: AttributeSet?
constructor(context: Context) : super(context) {
this.attrs = null
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
this.attrs = attrs
}
}