How do I access a constructor argument that is not a member variable in the init function?
I have a custom layout as shown below
class CustomComponent : FrameLayout {
constructor(context: Context?) : super(context)
constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
initAttrs(attrs)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
initAttrs(attrs)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
initAttrs(attrs)
}
init {
LayoutInflater.from(context).inflate(R.layout.view_custom_component, this, true)
}
fun initAttrs(attrs: AttributeSet?) {
val typedArray = context.obtainStyledAttributes(attrs, R.styleable.custom_component_attributes, 0, 0)
my_title.text = resources.getText(typedArray
.getResourceId(R.styleable.custom_component_attributes_custom_component_title, R.string.component_one))
typedArray.recycle()
}
}
Now for each constructor I have to call explicitly initAttrs(attrs)
as I cannot find a way to access it attrs
in my function init
.
Is there a way to access attrs
in init
, so I could call initAttrs(attrs)
from init
instead of explicitly calling it in each of the constructors?
source to share
Use the constructor with default arguments:
class CustomComponent @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : FrameLayout(context, attrs, defStyle) {
fun init {
// Initialize your view
}
}
The annotation @JvmOverloads
tells Kotlin to create three overloaded constructors so that they can be called in Java as well.
In your function, init
attrs
it becomes available as a nullable type:
fun init {
LayoutInflater.from(context).inflate(R.layout.view_custom_component, this, true)
attrs?.let {
val typedArray = context.obtainStyledAttributes(it, R.styleable.custom_component_attributes, 0, 0)
my_title.text = resources.getText(typedArray
.getResourceId(R.styleable.custom_component_attributes_custom_component_title, R.string.component_one))
typedArray.recycle()
}
}
Note the use it
in the block let
.
source to share