You cannot access the second constructor parameter from the init block. But there are at least two ways to implement similar functionality.
The first approach uses a single primary constructor with default parameters instead of several secondary constructors. In this case, you must apply the @JvmOverloads annotation to the constructor in order to force Kotlin to generate three different constructors.
class CustomCardView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout { init { LayoutInflater.from(context).inflate(R.layout.view_custom_card, this, true) if (attrs != null) { val a = context.obtainStyledAttributes(attrs, R.styleable.custom_card_view) if (a.hasValue(R.styleable.custom_card_view_command)) { var myString = a.getString(R.styleable.custom_card_view_command) } } } }
The seconds approach is two chain constructors and moving the contents of an init block into a constructor with three arguments.
class CustomCardView : FrameLayout { constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { LayoutInflater.from(context).inflate(R.layout.view_custom_card, this, true) if (attrs != null) { val a = context.obtainStyledAttributes(attrs, R.styleable.custom_card_view) if (a.hasValue(R.styleable.custom_card_view_command)) { var myString = a.getString(R.styleable.custom_card_view_command) } } } }
source share