我有一个自定义布局如下
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()
}
}
现在对于每个构造函数,我必须显式调用 initAttrs(attrs)
因为我找不到访问 attrs
的方法在我的 init
功能。
有什么方法可以访问 attrs
在 init
函数,所以我可以调用 initAttrs(attrs)
来自 init
而不是必须在每个构造函数中显式调用它?
最佳答案
使用带默认参数的构造函数:
class CustomComponent @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0
) : FrameLayout(context, attrs, defStyle) {
fun init {
// Initialize your view
}
}
@JvmOverloads
注释告诉 Kotlin 生成三个重载的构造函数,以便它们也可以在 Java 中调用。
在您的 init
函数中,attrs
可用作可空类型:
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()
}
}
注意 let
block 中 it
的用法。
关于android - 如何访问不是init函数中成员变量的构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44213958/