I want to send attrs through the super into View. (as shown in the first line) But the IDE doesn't want to take it; I am missing something from my code.
class BoxDrawingView(context: Context): View(context, attrs) {
var attrs: AttributeSet? = null
constructor(context: Context, attrs: AttributeSet): this(context) {
this.attrs = attrs
}
}
Can anyone help me with this? Thanks!
Try this:
class BoxDrawingView : View {
var attrs: AttributeSet? = null
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
this.attrs = attrs
}
}
The problem is that you don't have one single constructor that works for all cases. When this happens, you can avoid the normal constructor shorthand (i.e., declaring properties inline with the class declaration), make multiple constructors, and have each one delegate to a different superclass constructor.
You could also slightly rework things if you want to enable declaration of attrs
as a val
instead of a 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
}
}